Restart Container from Inside

Restart Container from Inside

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 ?

4

2 Answers

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= \
    && 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
3

reboot command works from withing container. I use this in my Go code inside docker

out, err = exec.Command("reboot").Output()
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.