How to create User/Database in script for Docker Postgres
📝 Tech Blog Post: How to Create User/Database in Script for Docker Postgres
Are you struggling to set up a custom user and database in a Docker Postgres container? Don't worry, I've got you covered! 🐘🐳
When using the official Postgres Docker image, you may encounter difficulties creating a user and database programmatically. The issue arises because the commands within the
/docker-entrypoint-initdb.d/ folder are executed before Postgres starts, resulting in a "No such file or directory" error message.
A Script to the Rescue!
To solve this problem, we can utilize a bash script to create the required user and database. Let's go step-by-step:
Create a new file called
make_db.shand include the following commands:
su postgres -c "createuser -w -d -r -s docker" su postgres -c "createdb -O docker docker"
Next, let's create a Dockerfile to build our custom Postgres image:
FROM library/postgres RUN ["mkdir", "/docker-entrypoint-initdb.d"] ADD make_db.sh /docker-entrypoint-initdb.d/
Resolving the Error
Now that we have our script and Dockerfile ready, let's address that pesky error. When running
docker logs -f db, you might see the following message:
createuser: could not connect to database postgres: could not connect to server: No such file or directory
To fix this, we need to ensure that the Postgres server is up and running before executing our script.
Delaying Execution with Docker Compose
To wait until Postgres is ready, we can utilize Docker Compose. Here's an example
version: '3' services: db: image: your-custom-postgres-image ports: - 5432:5432 environment: - POSTGRES_USER=docker - POSTGRES_PASSWORD=secret - POSTGRES_DB=docker command: bash -c "while ! pg_isready -h localhost -U docker; do sleep 1; done && /docker-entrypoint-initdb.d/make_db.sh"
command section, the
pg_isready command waits until the Postgres server is ready, and then our
make_db.sh script is executed.
Get Ready to Rock 'n' Roll! 🎸
That's it! By using the power of a bash script and Docker Compose, you can now easily create a user and database programmatically in your Docker Postgres container! 🚀
So, why wait? Start developing your amazing applications with Docker Postgres today and say goodbye to manual setup. Feel free to comment below and let me know if you found this guide helpful or if you have any questions. Happy coding! 😄