I am using a https://hub.docker.com/_/postgres/ (alpine based postgres container) for database setup. I have some a shell script which basically checks the version of software by running a psql query and compares it with the latest version, if there is a difference in version then pulls the latest sql files from github and updates the database. I want this shell script to run whenever the container starts. I tried to keep this script in /docker-entrypoint-initdb.d but later found that the scripts inside /docker-entrypoint-initdb.d do not run if the database is already initialized, so it does not solve my problem. I also tried using entrypoint: /custom-entrypoint-override.sh in my docker-compose file but then this script executes before the postgres is started and so the psql command in my shell script failed, so it also did not solve my problem. If anyone has any solution for this, please let me know. Thanks in advance.
1 Answer
To illustrate how to create a custom entrypoint script that'll run PSQL commands every time the container starts, here's what you can do:
Extract the docker-entrypoint.sh script from your image using the command
docker run --rm postgres:alpine cat /usr/local/bin/docker-entrypoint.sh > docker-entrypoint.sh
Edit the file and wrap your commands in the docker_temp_server_start and docker_temp_server_stop functions so Postgres is running but isn't accepting connections from outside the container. Here I've only shown the last bit of the script
EOM
else
cat <<-'EOM'
PostgreSQL Database directory appears to contain a database; Skipping initialization
EOM
fi
# run custom commands on container start
docker_temp_server_start "$@"
psql -U "$POSTGRES_USER" --list
docker_temp_server_stop
fi
exec "$@"
}
if ! _is_sourced; then
_main "$@"
fi
Here we run the psql -U "$POSTGRES_USER" --list command which will list the defined databases.
Mark the script as executable using chmod +x docker-entrypoint.sh.
Then you can create a custom image using a Dockerfile like this
FROM postgres:alpine
COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
Now, every time you run your custom Postgres image, it'll list the defined databases.
To run migrations, you'll need to expand the code to figure out what needs to be run.
docker_temp_server_startanddocker_temp_server_stopfunctions from the normal docker-entrypoint.sh script github.com/docker-library/postgres/blob/master/14/bullseye/…