Set the timed shutdown and startup of docker
Setting the timed shutdown and startup of containers in Docker can be achieved through a variety of methods.
Here are two common methods: using system-level timing tasks (such as cron) and using Docker-specific solutions.
Using Cron
1. Create a Cron Job:
- Open the terminal.
- enter
crontab -e
Edit the cron file for the current user.
Add the following line to define the time to start and stop. For example, stop the container at 2 a.m. every day and start the container at 7 a.m.:
0 2 * * * docker stop my_container_name 0 7 * * * docker start my_container_name
- Save and exit the editor.
- Cron will automatically load the new configuration.
2. Make sure Docker service is running:
- It is necessary to ensure that the Docker service is running within the scheduled time.
- If the system restarts, you may need to set the Docker service to start with the system.
Using Docker Compose
If you use Docker Compose to manage multiple containers, you can use Docker Compose and Cron to start or close the entire service group regularly.
1. Create or edit:
- Define your service.
- Save the file.
2. Create a Cron Job:
- Similar to the above, but this time the command will target the entire compose file.
Assume your file is located in/path/to/
, you can set it like this:
0 2 * * * docker-compose -f /path/to/ down 0 7 * * * docker-compose -f /path/to/ up -d
Using Docker Swarm
For more complex environments, such as using Docker Swarm, you can achieve similar timing startup and shutdown effects by updating the number of replicas of the service.
Update the number of service replicas:
You can create a script that adjusts the number of replicas of the service based on time.
For example, a simple bash script might look like this:
#!/bin/bash if [ "$1" = "up" ]; then docker service scale my_service=3 elif [ "$1" = "down" ]; then docker service scale my_service=0 fi
Then, you can call this script through Cron:
0 2 * * * /path/to/ down 0 7 * * * /path/to/ up
Things to note
- Time format: Cron's time format is minutes, hour, day, month, week 0 and 7 represent Sunday.
- Permissions: Make sure that the user executing these commands has sufficient permissions to control Docker.
- test: Before deploying in a production environment, verify that your cron job is working as expected in the test environment.
- log: Consider redirecting the output of the cron job to the log file for easier debugging and logging.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.