Postgresql import and export database using Docker

PostgreSQL, also known as Postgres, is a free and open-source relational database management system emphasizing extensibility and SQL compliance. Source

Export database

  1. Login to a system with psql installed
  2.  pg_dump --host=localhost --username=dbloginname --dbname=testdb --file=/tmp/testdb_bac.sql
  3. copy db to destination system

create dockerfile and container

firstly we create a dockerfile using the postgres docker image and copying the exported database into the new image.

Dockerfile



Authors:
  • Martin Büchner
FROM postgres
COPY fsidb_bac.sql /docker-entrypoint-initd.d/

to build the dockerfile use:

docker build -t fsidbpostgresql:latest . 

With docker images all locally saved images are shown and fsidbpostgresql:latest should now be visible.
Now we start the container using:

sudo docker run -d --name postgresfsidb -p 5432:5432 -e POSTGRES_PASSWORD=MySafePassword fsidbpostgresql:latest 

Make sure the port isn't already used on your docker hostsystem, if so you can bind 5432 onto another port of the hostsystem.

import database in container

Firstly connect to the shell of the docker container. All containers can be listed with docker container ls -a.

docker exec -it postgresfsidb bash

Before importing the fsidb_bac.sql a new database has to be created. Usercreation is optionally.
Start postgresql client:

psql -U postgres 

Create a new database with sql statement:

CREATE DATABASE newdb;

Quit the postgresql client with \q
Import the database as following:

psql -U postgres newdb < /docker-entrypoint-initd.d/fsidb_bac.sql


Authors:
  • Martin Büchner