A step by step how to start docker-compose container at boot

Photo by Onur Binay on Unsplash

Once create a docker container, we all hope the container can automatically by itself, also at the boot.

Here we will go through with docker-composeyaml config file, ex. docker-compose.yml .

At the basic of the yaml file

# docker-compose.yml exampleversion: "3"
service:
restart: always # the most important line for this post
image: xxxx #docker image
environment:
- key : value ...
ports:
- 8080:80

Let’s take a look at docker restart policy with 4 types :

Ref : https://docs.docker.com/config/containers/start-containers-automatically/#use-a-restart-policy

no : Do not automatically restart the container. (the default)

on-failure[:max-retries] : Restart the container if it exits due to an error, which manifests as a non-zero exit code. Optionally, limit the number of times the Docker daemon attempts to restart the container using the :max-retries option.

always : Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in restart policy details)

unless-stopped : Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.

With the basic docker command start a container:

$ docker run -d --restart <restart_policy> <docker_image>

Make sure docker daemon is enabled to launch at boot :

$ sudo systemctl start docker
$ sudo systemctl enable docker
$ sudo systemctl is-enabled docker # the output should be enabled

Check the docker container restart policy

$ docker inspect <container_id> | fgrep -i restart -A 5

if nothing is set to restart:

"AppArmorProfile": "docker-default",
"RestartPolicy": {
"Name": "",
"MaximumRetryCount":0
},
...

once we set the restart parameter:

"AppArmorProfile": "docker-default",
"RestartPolicy": {
"Name": "always",
"MaximumRetryCount":0
},
...

Now the container can restart by itself, once the pc / server is rebooted.

Hope this can could help and save a day off !!

Ref : https://stackoverflow.com/a/70991572

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
jason19970210

jason19970210

a graduate student in NCU in Taiwan with major in CSIE, Cybersecurity, also familiar in mobile development & UIUX & System Architecture Design