Victor
Victor

Reputation: 23932

How to run a periodic cleanup task in a Docker container

I have a container that runs an ASP.NET Core app in Ubuntu. The app generates a few temp files (in /tmp), and I would like to keep the temp folder clean deleting *.tmp files older than 10 minutes.

In a full server I can setup a systemd service/timer that does that, but it seems that systemd can't be run inside a container.

I have read about running cron jobs in Docker containers, but am not sure it is the standard way to run frequent commands in a Docker container.

What is the best way to run a periodic task along my application in a Docker container?

Upvotes: 1

Views: 510

Answers (1)

Antonio Petricca
Antonio Petricca

Reputation: 11026

My suggestion is to map the docker container folder to an external server folder by adding -v {{SERVER_MAPPED_TEMP_FOLDER}}:{{CONTAINER_INTERNAL_TEMP_FOLDER}} to the docker build command in order to keep temporary files outside the container where they can be managed.

Then schedule a daily cronjob on the server by sudo crontab -e and add 0 2 * * * rm {{SERVER_MAPPED_TEMP_FOLDER}}/{{OLD_LOG_FILE_GLOB}} (in this example it runs every day at 2:00 am).

Upvotes: 1

Related Questions