drmrbrewer
drmrbrewer

Reputation: 13029

Docker + Crontab: find container ID from service name for use in crontab

The context is that I'm trying to set up a cron job to back up a database within a postgres docker container. The crontab line I'm using is:

45 1 * * * docker exec e2fa9f0adbe0 pg_dump -Z 9 -U pguser -d pgdb | curl -u ftpuser:ftppwd ftp.mydomain.com/my-db-backups/db-backup_`date '+\%Y-\%m-\%d_\%H-\%M-\%S'`.sql.gz --ftp-create-dirs -T -

It works fine. But I'm trying to refine it because at present the container ID e2fa9f0adbe0 is hard-coded into the crontab, so it will break if ever the service under which the container placed is restarted, so that the container will re-appear under a new ID. On the other hand, the service name will always be the same.

So is there a way of altering the above cron command to extract the container ID from the service name (let's say my-postgres-service)?

Upvotes: 1

Views: 370

Answers (2)

olmpc
olmpc

Reputation: 81

You can use the following command to get the id from the name:

docker ps -aqf "name=my-postgres-service"

And the following to have more details about the options used above:

docker ps -h

So, the full crontab line would be:

45 1 * * * docker exec `docker ps -aqf name=my-postgres-service` pg_dump -Z 9 -U pguser -d pgdb | curl -u ftpuser:ftppwd ftp.mydomain.com/my-db-backups/db-backup_`date '+\%Y-\%m-\%d_\%H-\%M-\%S'`.sql.gz --ftp-create-dirs -T -

Upvotes: 1

drmrbrewer
drmrbrewer

Reputation: 13029

Well I tried to edit Olmpc's answer to make it more complete (and so that I can mark it as Accepted), but my edit was rejected (thanks). So I'll post my own answer:

To answer the actual question, the cron command can be altered as follows so that it is based on the service name (which is fixed) rather than the container ID (which is subject to change):

45 1 * * * docker exec `docker ps -qf name=my-postgres-service` pg_dump -Z 9 -U pguser -d pgdb | curl -u ftpuser:ftppwd ftp.mydomain.com/my-db-backups/db-backup_`date '+\%Y-\%m-\%d_\%H-\%M-\%S'`.sql.gz --ftp-create-dirs -T -

This is working nicely. Note: it relies on there being only one container associated with the service, so that only a single container ID is returned by docker ps -qf name=my-postgres-service.

Upvotes: 1

Related Questions