SoFunction
Updated on 2025-03-10

How to create a PostgreSQL database using Dockerfile

Download the basic image on the official website

[root@localhost ~]# docker pull postgres:latest

Create a project directory

[root@localhost ~]# mkdir /root/postgresql

Create a file called "Dockerfile"

[root@localhost ~]# vim Dockerfile
# Use the official PostgreSQL imageFROM postgres:latest
# Set environment variables (set database login password)ENV POSTGRES_PASSWORD=aczu102030
# Copy the files in the current directory to the // directory in the containerCOPY  //
# Expose the default port of PostgreSQLEXPOSE 5432
# Execute the command when the container startsCMD ["postgres"]

Create a file named

[root@localhost ~]# vim 
CREATE TABLE mytable (  
  id SERIAL PRIMARY KEY,  
  name VARCHAR(100)  
);  
INSERT INTO mytable (name) VALUES ('John'), ('Jane'), ('Doe');

Build with Dockerfile

[root@localhost postgres]# docker build -t my-postgres .  

Build a Docker image called my-postgres

Run PostgreSQL container

[root@localhost postgres]# docker run -d --name my-postgres-container -p 5432:5432 my-postgres

The background runs a container called my-postgres-container, which maps the host's port 5432 to the container's port 5432.

Allow remote connections to PostgreSQL containers

Enter the PostgreSQL container

[root@localhost postgres]# docker exec -it <container name or ID> bash

Allow PostgreSQL to listen to all addresses.

root@59fc0bb64dea:/# echo "host all  all    0.0.0.0/0  md5" >> /var/lib/postgresql/data/pg_hba.conf
root@59fc0bb64dea:/# exit

Restart the PostgreSQL container.

[root@localhost postgres]# docker restart 59fc0bb64dea

Connect with the correct username, password, and database name when connecting remotely.

This is the end of this article about how to use Dockerfile to create PostgreSQL database. For more related content on creating PostgreSQL databases, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!