How to execute commands while running this docker container?

501 Views Asked by At

I want to pull docker postgres image and create a database mydb in it. I am able to do it step by step like this

  1. docker run -d -p 5432:5432 --name containername -e POSTGRES_PASSWORD=password -d postgres:12.1

  2. docker exec -it containername /bin/bash

  3. psql -h localhost -U postgres

  4. CREATE database mydb;

I wanted to add these steps in a readme documentation. Is it possible to do everything in a single command when running the container itself? Tried something like below but couldn't succeed

docker run -d -p 5432:5432 --name terminals -e POSTGRES_PASSWORD=password -d postgres:12.1 psql -h localhost -U postgres; create database terminals

2

There are 2 best solutions below

0
bruegth On

You can mount a init script into container:

docker run -d -v /local-path/your-init.sql:/docker-entrypoint-initdb.d/your-init.sql -p 5432:5432 --name containername -e POSTGRES_PASSWORD=password postgres:12.1

your-init.sql:

CREATE database mydb;
0
pol92 On

Postgres official docker images (like postgres:12.1 you are currently using) come with a docker-entrypoint.sh script which is able to initialize the database based on env variables (documentation as also mentioned by @Zeitounator). So, in order to start postgres and initiate the database upon startup you need to add an extra env variable (POSTGRES_DB=mydb) when you run the image:

docker run -d -p 5432:5432 --name containername -e POSTGRES_PASSWORD=password -e POSTGRES_DB=mydb -d postgres:12.1