Docker is essential nowadays if you want to pack your applications and not depend on anything from the host machine. Actually, this a good practice when creating containers.
There are many ways to deploy a Docker container and one of those ways is to run the container inside a virtual machine (VM). I am doing exactly this to run some of my projects using a Ubuntu Virtual Machine hosted on Google Cloud.
But I have one need: schedule some commands from inside the container to run every single hour!
I started using the Container Optimized OS offered by Google but I could not schedule tasks on it using cron… so I decided to use a default Ubuntu VM.
The advantage to run a container inside a VM is that you can use cron at the VM to schedule background tasks that are important to your application. You’ll simple run docker exec commands to do whatever you need to accomplish inside the container.
Cron is easy to set up, but usually is not easy to debug if you are not familiar with how it works. The cron environment is different from the one you have at the command line.
Docker exec and cron
I tried to run a command in my container putting the following line in my /etc/crontab file:
The problem with this command is that I included the -it parameter on docker exec.
The -it flags indicates that my docker exec command needs a pseudo terminal and will run in interactive mode. Cron does not attach to terminals by default.
In order to run a docker exec command from cron, DO NOT USE the -it flag and you’ll be good!
Running docker exec from cron. Image: Samuel Lee Toepke
After the modification, the following cron command worked flawlessly!
It is very easy to run many different commands inside your container using the cron from your VM, especially in small projects!
Docker: failed to build: max depth exceeded
Docker + VirtualBox on Windows 10
How to create a virtual environment for Python in Ubuntu
WordPress from PHP 5.6 to PHP 7.2! Better performance?