bashdockereofalpine-linuxdocker-entrypoint

Container date won't update in entrypoint script


I built a container using the docker-compose script below:

services:
  client:
    image: alpine
    environment:
      - BACKUP_ENABLED=1
      - BACKUP_INTERVAL=60
      - BACKUP_PATH=/data
      - BACKUP_FILENAME=db_backup
    networks:
      - dbnet
    entrypoint: |
      sh -c 'sh -s << EOF
      apk add --no-cache mysql-client
      while true
        do
          then
            sleep $$BACKUP_INTERVAL
            echo "$$(date +%FT%H.%M) - Making Backup to : $$BACKUP_PATH/$$(date +%F)/$$BACKUP_FILENAME-$$(date +%FT%H.%M).sql.gz"
            mysqldump -u root -ppassword -h dblb --all-databases | gzip > $$BACKUP_PATH/$$(date +%F)/$$BACKUP_FILENAME-$$(date +%FT%H.%M).sql.gz
        done
      EOF'

But I encounter an issue where the date won't be updated and causes the loop keep backup to the same created file.

Every 60s the log will some the same date value. Here the container's log:

container log

The same thing happened when I tried to manually write the script inside the container:

enter image description here

The timestamp always displays correctly when I only type date inside the container console.

Why won't the date update? What did I miss in the script?


Solution

  • Why won't the date update?

    Because it is expanded by outer shell. Compare a shell script:

    #!/bin/sh
    # in a script
    # this is running inside a shell
    cat <<EOF   # cat just prints data
    $(date)     # not cat, **but the shell**, expands $(date)
    EOF
    

    vs:

    sh -c '
    # this is running inside a shell
    sh -s <<EOF     # sh -s executes input data
    echo $(date)    # not sh -s, but **the outer shell**, expands $(date). ONCE
    EOF
    '
    

    That sh -c sh -s and entrypoint is all unorthodox, just run the command that you want to run.

    command:
       - sh
       - -c
       - |
         apk add --no-cache mysql-client
         while sleep $$BACKUP_INTERVAL; do            
            echo "$$(date +%FT%H.%M) - Making Backup to : $$BACKUP_PATH/$$(date +%F)/$$BACKUP_FILENAME-$$(date +%FT%H.%M).sql.gz"
         done