A Step-by-Step Guide How to Start docker-compose Container at Boot

jason19970210
2 min readMar 13, 2022

--

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-compose yaml 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

--

--

jason19970210
jason19970210

Written by jason19970210

a slashie from Taiwan 🇹🇼! Fields: Software Dev, Networking, Digital Forensics Investigator, SA, UIUX, 3D Design, etc.