Yes, Docker provides a built-in way to automatically start containers on Docker daemon restart or system boot using the --restart policy when you run a container. Here’s how it works:
1. Using the --restart Policy
When you start a container, you can specify a restart policy:
- no (default): Do not automatically restart the container.
- always: Always restart the container if it stops. If it is manually stopped, it will be restarted only when Docker daemon restarts or the container itself is manually restarted.
- unless-stopped: Similar to
always, except that when the container is stopped (manually), it is not restarted even after Docker daemon restarts.
- on-failure: Restart the container only if it exits with a non-zero exit status. Optionally, you can limit the number of restart attempts.
Example
docker run -d --restart unless-stopped your_image_name
Or, for an existing container:
docker update --restart unless-stopped your_container_name
2. With Docker Compose
In your docker-compose.yml, you can set the restart policy for each service:
services:
myservice:
image: your_image_name
restart: unless-stopped
Then run:
docker-compose up -d
3. Systemd (Advanced/Optional)
If you want even more control, you can create a systemd service for your container, but for most use cases, the Docker restart policies are sufficient.
Summary Table
| Policy | On Docker Restart | On Container Exit | On Manual Stop |
|---|
| no | No | No | No |
| always | Yes | Yes | Yes |
| unless-stopped | Yes | Yes | No |
| on-failure | Yes (if failed) | Yes (if failed) | No |
In most cases, --restart unless-stopped is the best choice for services you want to always run unless you explicitly stop them.
Let me know if you need a specific example or help with your setup!