In Docker, the primary method for configuring automatic container restart is by utilizing restart policies. Docker provides several distinct restart policies that you can select based on your requirements. These policies include:
- no: This is the default setting, where the container does not restart automatically upon exit.
- always: Regardless of the container's exit status, the container will always restart.
- unless-stopped: The container will always restart unless explicitly stopped by the user, even during the Docker daemon's startup or restart.
- on-failure: The container restarts only when it exits abnormally (exit status is non-zero). You can optionally specify the maximum number of restart attempts.
For instance, if you want your container to automatically attempt restarts when it encounters errors, use the --restart on-failure option when running the container. You can also add an optional limit on the number of restart attempts, such as:
bashdocker run --restart=on-failure:5 your-image
This command instructs Docker to attempt restarting the container up to five times, exclusively when the container's exit code is non-zero.
If you require the container to restart regardless of the exit status, employ the always policy:
bashdocker run --restart=always your-image
This ensures the container always attempts to restart after stopping, which is particularly valuable in production environments to maintain continuous operation of critical services.
Consider a practical scenario: suppose you have a web server container and want it to automatically restart after crashing to continue providing service. Use the following command:
bashdocker run --restart=always -d -p 80:80 your-webserver-image
This command sets the always restart policy, guaranteeing the web server restarts automatically in any exit scenario. The -d parameter runs the container in the background, and -p 80:80 maps port 80 inside the container to port 80 on the host for external access.
By implementing this configuration, you can enhance the stability and reliability of container operations.