How to launch a new instance of a Docker container on web request in Docker Swarm / Kubernetes?

10/17/2018

I have a web API running on a Docker container. I want to implement a solution in Kubernetes/DockerSwarm such that a new instance of the container is created everytime the API is called. How can that be achieved ?

-- Satya Prakash
docker
docker-swarm
kubernetes

1 Answer

10/17/2018

For this you need to control the docker swarm from inside the container itself. This can be done in two steps:

  1. install the docker inside the container. This depends on the container image. A solution can be like this:

    RUN apt-get -yqq update && apt-get -yqq install docker.io 56 && usermod -g docker jenkins

  2. mount the docker socket inside the container. For example, if you start the container manually, you need something like this:

    docker run -it -v /var/run/docker.sock:/var/run/docker.sock -v /usr/bin/docker:/usr/bin/docker ubuntu:latest bash

Now, you can run docker commands inside the container. You can, for example, inspect a service or scale it to a bigger number of replicas.

You should note however that this solution is not very safe, if someone gains access to your container then it has access to the entire swarm, so be aware!

-- Constantin Galbenu
Source: StackOverflow