Restart container from inside

10,994

You just need to install docker client when building your docker images and map /var/run/docker.sock when running a new container to enable docker client inside the container to connect the docker daemon on the host, then you can use docker command just like on the host.

First, add commands to install docker-ce in your Dockerfile:

FROM centos:7.8.2003

ENV DOCKER_VERSION='19.03.8'

RUN set -ex \
    && DOCKER_FILENAME=https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz \
    && curl -L ${DOCKER_FILENAME} | tar -C /usr/bin/ -xzf - --strip-components 1 docker/docker

Then, build a new image and run a new container using it:

$ docker build --tag docker-in-docker:v1 .
$ docker run -dit \
             --name docker-in-docker \
             -v /var/run/docker.sock:/var/run/docker.sock:ro \
             docker-in-docker:v1 bash

Now, you can operate docker-daemon (on the host) inside docker container.

$ docker exec -it docker-in-docker docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS               NAMES
bdc2d81b2227        docker-in-docker:v1   "bash"                   8 seconds ago       Up 7 seconds                            docker-in-docker
# just restart the container docker-in-docker in the container docker-in-docker:
$ docker exec docker-in-docker docker restart docker-in-docker
Share:
10,994
quantCode
Author by

quantCode

Updated on July 25, 2022

Comments

  • quantCode
    quantCode almost 2 years

    On a batch job, Am doing a large number of operations inside a docker.

    Is there to send a command from inside so docker can come back as if it were just started ?

  • halfer
    halfer about 6 years
    This approach will work, and can be appropriate in some circumstances. However, it will lose all the security isolation of the container, and essentially give it root access to the whole host (including access to anything, including containers, running on it).
  • Mikl
    Mikl over 5 years
    Explain please, why docker client have write access to docker host with only read-only permissions on docker.sock?
  • OneCricketeer
    OneCricketeer over 4 years
    This just kills the container. You'd have to use external scheduling to get it to actually come back
  • Sunchezz
    Sunchezz almost 3 years
    @Mikl In most prod-environments you shouldn't do it. You expose a lot of information and probably with a bit of knowledge the attacker is still able to gain root access through it. Also an attacker could start new containers and use your machine for a bot-net ;) raesene.github.io/blog/2016/03/06/The-Dangers-Of-Docker.sock