How do I make a Docker container start automatically on system boot?
Supposed I have a Docker container that I want to run, then I can call
$ docker run ...
and everything is fine. Is there a built-in way to run a container in a way that it will be restarted automatically, if the system crashes and reboots?
If so, is this also available in Docker Compose?
Solution 1:
Yes, docker has restart policies such as docker run --restart=always
that will handle this. This is also available in the compose.yml config file as restart: always
.
Solution 2:
If you want the container to be started even if no user has performed a login (like the VirtualBox VM that I only start and don't want to login each time). Here are the steps I performed to for Ubuntu 16.04 LTS. As an example, I installed a oracle db container:
$ docker pull alexeiled/docker-oracle-xe-11g
$ docker run -d --name=MYPROJECT_oracle_db --shm-size=2g -p 1521:1521 -p 8080:8080 alexeiled/docker-oracle-xe-11g
$ vim /etc/systemd/system/docker-MYPROJECT-oracle_db.service
and add the following content:
[Unit]
Description=Redis container
Requires=docker.service
After=docker.service
[Service]
Restart=always
ExecStart=/usr/bin/docker start -a MYPROJECT_oracle_db
ExecStop=/usr/bin/docker stop -t 2 MYPROJECT_oracle_db
[Install]
WantedBy=default.target
and enable the service at startup
sudo systemctl enable docker-MYPROJECT-oracle_db.service
For more informations https://docs.docker.com/engine/admin/host_integration/
Solution 3:
The default restart policy is no
.
For the created containers use docker update
to update restart policy.
docker update --restart=always 0576df221c0b
0576df221c0b
is the container id.