Start Docker Containers Automatically- 3 mins
Starting your Docker containers automatically using
After your Docker containers are set up and running, you might need to be able to start some of them automatically on a reboot or a crash. There are several ways of getting this done.
One of them is to use restart policies provided by Docker. They can be set to control whether your containers start automatically when they exit, or when Docker restarts.
Alternatively, you can use a process manager such as
supervisor instead. In this post, I want to show you how it is done with
Create the Service File
To create a service file that will be used by
systemctl command), we will first need to get your container name. This can be done by running the following command in your shell:
The output will look something like this. Select the right container from the list, and note its name in the last column. In this example, we will be using
Now, we will need to create a file (choose an appropriate file name for the service):
Paste the following into the file. Set a proper
Description, and make sure to update the container name in
A couple of notes about the script above:
- This file is called a unit file for
- Make sure you don’t have any extra line brakes within the sections, like
-aoption in the Docker command for
ExecStartmakes sure it is running in attached mode, i.e., attaching STDOUT/STDERR and forwarding signals.
-toption in the Docker command for
ExecStopspecifies seconds to wait for it to stop before killing the container.
Activate the Service
Before we can activate the service we have created, we need to reload the unit file. You will also need to run this command anytime you do any modifications to the unit files:
To activate the service run the following commands (remember to change the service name):
To disable the service run the following commands (remember to change the service name):
Changes will come to effect on a reboot:
Now you should have a container that will start on a server reboot, Docker restart, or a crash. Congratulations!
As a next step, you might want to look at (external documentation links):
- Adding some more parameters to the unit file.