Configuring Docker Service and Containers for Automatic Restart on Linux System Boot
To maintain application continuity after system reboots, it is essential to configure both the Docker service and individual containers to restart automatically. This guide covers the necessary steps for setting up automatic restarts in a Linux environment.
Configuring Docker Service for Automatic Startup
1. Verify Docker Service Status
First, check the current status of the Docker service to ensure it is installed and operational.
sudo systemctl status docker
If the Docker service is not runing, start it with the following command:
sudo systemctl start docker
2. Enable Docker Service for Automatic Startup
Use the systemctl commend to configure the Docker service to start automatically upon system boot.
sudo systemctl enable docker
After executing this command, the Docker service will launch automatically when the system starts. Confirm the setting with:
sudo systemctl is-enabled docker
If the output is enabled, the Docker service is confiugred for automatic startup.
Setting Up Docker Containers for Automatic Restart
Beyond enabling the Docker service, ensure containers restart automatically when the service starts. Docker offers multiple restart policies to suit different needs.
1. Restart Policy Options
- no: Containers do not restart automatically (default).
- on-failure: Restart containers only if they exit with a non-zero status code.
- always: Always restart containers regardless of exit status.
- unless-stopped: Always restart containers unless they are manually stopped.
2. Applying Restart Policies to Containers
Set the restart policy when launching a container using the --restart option. For example, to configure a container to restart under all condition:
docker run -d --restart always my-container
For containers already running, update their restart policy with the docker update command:
docker update --restart always <container_id>
Example: Configuring an Nginx Container for Automatic Restart
This example demonstrates setting up an Nginx container to restart automatically when the Docker service starts.
1. Launch Nginx Container with Restart Policy Set to always:
docker run -d --name my-nginx --restart always nginx
2. Verify the Container's Restart Policy:
docker inspect -f '{{.HostConfig.RestartPolicy.Name}}' my-nginx
If the output is always, the restart policy is correctly configured.
Key Steps Summary
- Use systemctl enable docker to set the Docker service for automatic startup.
- Apply appropriate restart policies with the --restart opsion when launching containers.
- Update restart policies for existing containers using the docker update command.