Yes, you can configure Docker containers to automatically start when the Docker service restarts or when the host system boots. This is typically done using Docker's restart policies and ensuring that Docker itself starts on boot. Here's how to achieve this:
1. Using Docker Restart Policies
Docker allows you to set a restart policy when starting or updating a container. The most common policies are:
no: Never restart (default).
on-failure: Restart only if the container exits with a non-zero exit code.
always: Always restart, regardless of exit status.
unless-stopped: Always restart, unless the container was manually stopped.
Example 1: Start a Container with always Policy
docker run -d --restart=always --name my_container my_image
Example 2: Update an Existing Container to Use always Policy
docker update --restart=always my_container
2. Docker Compose
If you use docker-compose, add the restart: always directive to your docker-compose.yml file for each service:
version: '3'
services:
my_service:
image: my_image
restart: always # <-- Add this line
Then start your containers with:
docker-compose up -d
3. Ensure Docker Starts on Boot
The restart policies above only work if Docker itself is running. To ensure Docker starts automatically on system boot:
On Linux:
Check if Docker is set to start on boot:
sudo systemctl is-enabled docker
If it’s not enabled, enable it:
sudo systemctl enable docker
On macOS/Windows:
Docker Desktop typically starts automatically when the system boots, but you can verify this in your system's startup applications.
4. Troubleshooting
- Containers not restarting?
Check the container's logs for errors:
docker logs my_container
- Docker not starting on boot?
Ensure Docker's dependencies (e.g., containerd, runc) are running and properly configured.
Summary
- Use
--restart=always (or unless-stopped) when starting containers.
- For Docker Compose, use
restart: always in the docker-compose.yml.
- Ensure Docker is set to start on boot for the host system.
This setup ensures containers restart automatically after Docker restarts or system reboots.