How can I access Docker environment variables from a cron job?

Better Stack Team
Updated on May 26, 2023

To access Docker environment variables from a cron job, you can use the -e option when running the docker run command to pass the environment variables to the container, and then use them in your cron job command.

Here's an example of how you can do it:

  • Define your environment variable(s) when running your Docker container:
 
docker run -e VAR_NAME=VAR_VALUE my-docker-image
  • In your cron job command, use the environment variable(s) like this:
 
0 0 * * * /usr/bin/env VAR_NAME=$VAR_NAME /path/to/command

This will set the VAR_NAME environment variable for the env command, which will then be available for the rest of the command. Replace /path/to/command with the command you want to run.

Here's a breakdown of the format:

  • The first 0 represents the minute (0-59)
  • The second 0 represents the hour (0-23)
  • The * in the third, fourth, and fifth positions represent the day of the month, the month, and the day of the week (respectively). Using * means the job will run every day of the month, every month, and every day of the week.
  • The sixth field is the command to be executed.
  • The /usr/bin/env command is used to set the environment variable for the command that follows.
  • The VAR_NAME=$VAR_NAME sets the environment variable in the command. Replace VAR_NAME with the name of the environment variable you want to use.

So the cron job in the above format will run the command with the environment variable defined in the Docker container.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack