Running PostgreSQL in a Docker Container

Learn how to run PostgreSQL inside a Docker container for local development without installing it directly on your machine

Running PostgreSQL inside a Docker container gives you a fully functional database without permanently installing PostgreSQL on your computer. This approach keeps your system clean, lets you experiment freely, and makes it easy to reset your database to a known state whenever you need to start over.

Why Use Docker for PostgreSQL

Installing PostgreSQL directly on your operating system changes your machine in ways that are hard to undo completely. The installer adds background services, creates system users, and places files in system directories. If you later want a different PostgreSQL version, or if the installation becomes corrupted, cleaning up can be frustrating.

A Docker container solves this by packaging PostgreSQL, along with everything it needs, into an isolated unit. The database runs inside the container. Your operating system only sees Docker itself. When you want to remove PostgreSQL, you delete the container and its data volume. Nothing is left behind.

What Is a Container:

A container is a lightweight, isolated environment that bundles an application with its dependencies. It behaves like a small virtual machine but shares your computer's operating system kernel. You already learned about container basics earlier in this chapter, so this page focuses specifically on running PostgreSQL inside one.

This approach also makes it practical to keep multiple PostgreSQL versions side by side. You can run PostgreSQL 17 in one container and PostgreSQL 18 in another, each with its own port and data, without any conflict.

Before You Begin

Docker needs to be installed and running before you can start a PostgreSQL container. You can verify this by opening a terminal and running two commands.

First, check that the Docker client is available:

docker --version

You should see output similar to:

Docker version 29.9.3

The exact version number will differ on your machine. What matters is that the command succeeds without an error.

Second, check that the Docker daemon is running and responding:

docker ps

This command lists running containers. If the daemon is working, you will see a header row even if no containers are running:

CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

If you see an error message about the daemon not running, start Docker Desktop and wait a few seconds before trying again.

Docker Daemon Not Running:

Every Docker command fails when the daemon is not active. On macOS and Windows, open the Docker Desktop application and wait until its status indicator turns green. On Linux, run sudo systemctl start docker if Docker was installed as a system service.

Your First PostgreSQL Container

The fastest way to get PostgreSQL running in Docker involves two commands: one to download the PostgreSQL image, and one to start a container from it.

An image is a read-only template that contains the PostgreSQL software and its default configuration. A container is a running instance created from that image.

1

Step 1: Pull the PostgreSQL Image

The docker pull command downloads the image from Docker Hub, the public registry where official images are hosted.

docker pull postgres:18

Docker downloads several layers that together form the PostgreSQL image. The :18 suffix is a tag that pins the image to PostgreSQL version 18. You will see progress output as each layer downloads, followed by a confirmation that the image is up to date.

2

Step 2: Run the Container

Now create a running container from the image. This command includes several flags that control how the container behaves:

docker run --name postgres-local -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres:18

The command returns a long hexadecimal string. That string is the container ID, which Docker uses internally to identify this specific container.

3

Step 3: Verify the Container Is Running

Run docker ps again to confirm the container started successfully:

docker ps

You should see your container listed with a status of Up:

CONTAINER ID   IMAGE        COMMAND                  CREATED         STATUS         PORTS                    NAMES
a1b2c3d4e5f6   postgres:18  "docker-entrypoint.s…"   5 seconds ago   Up 4 seconds   0.0.0.0:5432->5432/tcp   postgres-local
4

Step 4: Test the Database Connection

Use docker exec to run a command inside the running container. The psql tool is bundled with the PostgreSQL image:

docker exec -it postgres-local psql -U postgres

You should see the PostgreSQL interactive terminal:

psql (18.6)
Type "help" for help.
postgres=#

Type \q and press Enter to exit the PostgreSQL prompt.

Setup Complete:

If you reached the postgres=# prompt, your PostgreSQL container is fully operational. You now have a working local database running in Docker.

Understanding the docker run Command

The command you just executed combines several important options. Each one controls a different aspect of how the container operates.

The --name Flag

docker run --name postgres-local ...

The --name flag assigns a human-readable name to the container. Without it, Docker generates a random name like nostalgic_hopper. Choosing your own name makes every subsequent command easier, because you reference the container by name instead of by its long hexadecimal ID.

Think of the container name like a hostname for a server. Instead of remembering an IP address, you use a friendly label.

The -e Flag and Environment Variables

docker run ... -e POSTGRES_PASSWORD=mysecretpassword ...

The -e flag sets an environment variable inside the container. Environment variables are key-value pairs that processes read at startup to configure themselves. The PostgreSQL image checks for several specific environment variables when it initializes.

The only variable that is strictly required is POSTGRES_PASSWORD. Without it, the container refuses to start and exits immediately with an error.

Missing POSTGRES_PASSWORD:

If you forget to set POSTGRES_PASSWORD, the PostgreSQL container exits immediately. Run docker logs postgres-local to see an error message explaining that a password is required. You must remove the failed container and create a new one with the variable set.

The -p Flag and Port Mapping

docker run ... -p 5432:5432 ...

The -p flag publishes a container port to your host machine. The syntax is host-port:container-port.

PostgreSQL listens on port 5432 inside the container by default. The -p 5432:5432 mapping makes that same port available on your computer. When a program on your host connects to localhost:5432, Docker forwards that connection to the container's port 5432.

The two numbers do not have to match. You could map host port 6000 to container port 5432 with -p 6000:5432. Then applications on your host would connect to localhost:6000, and Docker would forward the traffic to PostgreSQL inside the container.

The -d Flag and Detached Mode

docker run ... -d postgres:18

The -d flag runs the container in detached mode, which means it runs in the background. Your terminal returns to the prompt immediately instead of attaching to the container's output.

Without -d, the container runs in the foreground and prints PostgreSQL's logs directly to your terminal. This is occasionally useful for debugging, but for everyday development, detached mode is more convenient.

You can view the logs of a detached container at any time with:

docker logs postgres-local

Configuring the Database with Environment Variables

The official PostgreSQL image supports several environment variables that control how the database initializes. These variables are only read the first time a container starts with an empty data directory. Once the database is initialized, changing the variables has no effect unless you delete the data volume and start fresh.

The Three Core Variables

The most commonly used variables are POSTGRES_USER, POSTGRES_PASSWORD, and POSTGRES_DB.

POSTGRES_USER sets the name of the default superuser account. If you omit it, the image defaults to the user postgres.

POSTGRES_PASSWORD sets the password for that superuser. This variable is mandatory.

POSTGRES_DB creates an additional database with the specified name when the container initializes. If you omit it, only the default postgres database exists.

Here is a more complete example that sets all three:

docker run --name postgres-dev \
  -e POSTGRES_USER=appuser \
  -e POSTGRES_PASSWORD=devpassword \
  -e POSTGRES_DB=myapp \
  -p 5432:5432 \
  -d postgres:18

This command creates a container named postgres-dev with a superuser named appuser, a password of devpassword, and a database named myapp. When Axum connects to this database later, it will use these credentials.

Why Multiple Databases Are Useful

The default postgres database is a system database used for administrative tasks. Creating a separate application database keeps your app's tables separate from PostgreSQL's internal bookkeeping.

If you are working on multiple projects, you might create one container per project, each with its own database name:

docker run --name project-alpha-db \
  -e POSTGRES_USER=alpha \
  -e POSTGRES_PASSWORD=alpha123 \
  -e POSTGRES_DB=alpha_app \
  -p 5433:5432 \
  -d postgres:18

Notice that this container maps host port 5433 to container port 5432. The first container still occupies host port 5432, so the second one uses a different host port. Both containers can run simultaneously without conflict because PostgreSQL runs on port 5432 inside each container, but the host ports are different.

Environment Variables Are Only Read on First Start:

The PostgreSQL image reads POSTGRES_USER, POSTGRES_PASSWORD, and POSTGRES_DB only when initializing an empty data directory. If you stop a container and restart it with different environment variables, those changes are ignored. To change these values, you must delete the container and its data volume, then create a new container.

Port Mapping in Detail

Port mapping deserves its own explanation because it is the mechanism that makes the containerized database reachable from your host.

Inside the container, PostgreSQL listens for connections on port 5432. That port is only visible inside the container's network namespace, which is a private network space that containers use by default. Programs running on your host cannot see it directly.

Docker's port publishing creates a bridge. The -p flag tells Docker to listen on a port on your host and forward all traffic from that port to a port inside the container.

Here is what happens when you run:

docker run ... -p 5432:5432 ... postgres:18
  1. Docker starts the container and gives it its own network namespace.
  2. PostgreSQL inside the container binds to port 5432 within that namespace.
  3. Docker opens port 5432 on your host's network interface.
  4. When a program on your host connects to localhost:5432, Docker intercepts that connection and forwards it to the container's port 5432.

This is why docker exec works even without port mapping. The docker exec command runs a process inside the container's own namespace, so it bypasses the host network entirely and connects directly to PostgreSQL as if it were running locally inside the container.

Choosing a Different Host Port

If port 5432 is already in use on your host - perhaps because you installed PostgreSQL natively before switching to Docker - you can map a different host port:

docker run --name postgres-alt \
  -e POSTGRES_PASSWORD=secret \
  -p 6000:5432 \
  -d postgres:18

Now applications on your host connect to localhost:6000, and Docker forwards the traffic to port 5432 inside the container.

Port Conflicts Cause Failures, Not Silent Success:

If you map a host port that is already occupied, docker run fails with an error like Bind for 0.0.0.0:5432 failed: port is already allocated - Docker never starts the container on an occupied port. If your container did start but connections to localhost:5432 reach a different database, a native PostgreSQL installation is likely listening on that port instead. Find it with lsof -i :5432 (or netstat -ano | findstr :5432 on Windows), stop it, or map a different host port.

Keeping Data Safe with Volumes

By default, all files created inside a container exist only as long as the container exists. When you remove the container, everything inside it is deleted. For a database, that means all your tables, rows, and indexes vanish.

This behavior is intentional. Containers are designed to be disposable. But for a database, you usually want the data to survive container restarts and even container removal.

The solution is a Docker volume. A volume is a storage location managed by Docker that exists independently of any single container.

Named Volumes

The simplest approach uses a named volume. You give the volume a name, and Docker manages where the data actually lives on your filesystem.

docker run --name postgres-persistent \
  -e POSTGRES_PASSWORD=secret \
  -e POSTGRES_DB=myapp \
  -p 5432:5432 \
  -v postgres-data:/var/lib/postgresql/data \
  -d postgres:18

The -v flag has the syntax volume-name:container-path. The container path /var/lib/postgresql/data is where PostgreSQL stores its data files inside the container.

When this container starts for the first time, Docker creates a volume named postgres-data and mounts it at the specified path inside the container. PostgreSQL writes its data files to that path, which means they land in the volume.

If you stop and remove this container, the volume remains. When you create a new container with the same volume name, the new container's PostgreSQL finds the existing data files and continues where the previous container left off.

Data Persists Across Container Recreation:

Volumes make it safe to remove containers. Run docker rm postgres-persistent and then start a new container with the same -v postgres-data:/var/lib/postgresql/data flag. Your tables and rows are still there.

Bind Mounts as an Alternative

A bind mount maps a directory on your host filesystem directly into the container. This is useful when you want to inspect or back up the database files easily.

docker run --name postgres-bind \
  -e POSTGRES_PASSWORD=secret \
  -p 5432:5432 \
  -v "$(pwd)/pgdata:/var/lib/postgresql/data" \
  -d postgres:18

This maps the pgdata directory in your current working directory to the container's data path. The $(pwd) syntax expands to your current directory path, which Docker requires for bind mounts.

Bind mounts are convenient for local development because you can browse the data files directly. However, they are less portable than named volumes because they depend on a specific directory existing on your host.

Viewing Existing Volumes

To see all volumes Docker has created, run:

docker volume ls

You should see output similar to:

DRIVER    VOLUME NAME
local     postgres-data

To remove a volume, you must first remove the container that uses it:

docker rm postgres-persistent
docker volume rm postgres-data

Removing a Volume Deletes Data Permanently:

The docker volume rm command permanently deletes everything stored in that volume. There is no undo. Only remove a volume when you are certain you no longer need the data inside it.

Connecting to PostgreSQL from Your Host

You now have PostgreSQL running in a container with its port published to your host. The next step is connecting to it from outside the container to run queries or manage your database.

Connecting from Inside the Container

The simplest connection method uses docker exec, which runs a command inside the running container:

docker exec -it postgres-local psql -U postgres

The -it flag combines -i (interactive) and -t (allocate a pseudo-terminal), which together allow you to type into the PostgreSQL prompt. The -U postgres part tells psql to connect as the user named postgres.

This method works even if you did not publish any ports, because it bypasses the network entirely and runs psql directly inside the container's own environment.

To connect to a specific database, add the database name after the options:

docker exec -it postgres-local psql -U postgres -d myapp

Connecting from Your Host Using psql

If you have the PostgreSQL client tools installed on your host, you can connect over the network using the published port:

psql -h localhost -p 5432 -U postgres -d myapp

The -h localhost tells psql to connect to your host machine, which Docker then forwards to the container. The -p 5432 specifies the port, which matches the host port you published.

When prompted, enter the password you set in POSTGRES_PASSWORD.

If you have psql installed on your host, use it to verify that port mapping works correctly. Run:

psql -h localhost -p 5432 -U postgres -d myapp

When prompted for a password, type the value you set in POSTGRES_PASSWORD. You should see the myapp=# prompt, which confirms that your host can reach PostgreSQL through the published port.

Verifying the Database Is Reachable Without a Client

If you do not have psql installed on your host and do not want to use a GUI tool, you can verify the port mapping with a simple network check:

docker exec postgres-local pg_isready -U postgres

This command runs pg_isready, a lightweight PostgreSQL health check tool, inside the container. The output confirms that PostgreSQL is accepting connections:

/var/run/postgresql:5432 - accepting connections

Port Mapping Working Correctly:

If psql -h localhost connects successfully, your port mapping is working. Traffic from your host is reaching PostgreSQL inside the container through Docker's network bridge.

Managing Container Lifecycle

Your PostgreSQL container behaves like a lightweight service that you can start, stop, and remove as needed.

Stopping a Container

Stopping a container shuts down PostgreSQL gracefully without deleting any data:

docker stop postgres-local

The container disappears from docker ps output, but its files remain intact. You can confirm it still exists by listing all containers, including stopped ones:

docker ps -a

Starting a Stopped Container

To bring a stopped container back up:

docker start postgres-local

The container resumes with the same configuration, environment variables, and data it had before stopping.

Restarting a Container

Restarting is equivalent to stopping and then starting in one command:

docker restart postgres-local

This is useful when you change a configuration file and need PostgreSQL to re-read it.

Removing a Container

Removing a container permanently deletes the container itself, including its writable layer. If you attached a volume, the volume survives:

docker stop postgres-local
docker rm postgres-local

If the container is still running, you can remove it in one step with the force flag:

docker rm -f postgres-local

Removing a Container Does Not Remove Its Volume:

Running docker rm deletes the container but keeps any named volumes you attached. This is usually what you want, because the data persists. If you also want to delete the data, you must run docker volume rm postgres-data separately.

Using Docker Compose for PostgreSQL

The docker run command works well for a single container, but it becomes unwieldy when you have many options. Docker Compose lets you define containers in a YAML file instead, which is easier to read, version, and share.

YAML is a human-readable data format that uses indentation to represent structure. Docker Compose reads a file named docker-compose.yml or compose.yml and creates all the containers it describes.

Create a file named docker-compose.yml in an empty directory:

docker-compose.yml
services:
  db:
    image: postgres:18
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: myapp
    ports:
      - "5432:5432"
    volumes:
      - postgres-data:/var/lib/postgresql/data
volumes:
  postgres-data:

This file describes one service named db that uses the postgres:18 image. The environment section lists the same variables you would pass with -e flags. The ports section maps host port 5432 to container port 5432. The volumes section mounts a named volume at the data path, and the top-level volumes section declares that volume.

To start the service:

docker compose up -d

Docker Compose reads the YAML file, creates the volume if it does not exist, starts the container in detached mode, and prints a summary:

[+] Running 2/2
 ✔ Volume "myproject_postgres-data"  Created
 ✔ Container myproject-db-1  Started

The container name is derived from the directory name and the service name. If your directory is named myproject, the container is myproject-db-1 and the volume is myproject_postgres-data. Compose prefixes both with the project name, which defaults to the directory name, so two projects using the same service and volume names never share containers or data.

To stop and remove the container while keeping the volume:

docker compose down

To stop the container, remove it, and also delete the volume:

docker compose down -v

docker compose down -v Deletes Data:

The -v flag on docker compose down removes named volumes declared in the Compose file. This permanently deletes all data stored in those volumes. Use it only when you want a completely fresh database.

Why Use Compose Instead of docker run

The Compose approach has several advantages for local development. The entire configuration lives in a file that you can commit to version control. Other developers can clone your repository, run docker compose up -d, and have the exact same database setup without needing to remember long command lines.

Compose also scales naturally. If your project later needs a Redis instance or a mail server alongside PostgreSQL, you add another service to the same file.

The trade-off is that Compose introduces an extra file and a slightly different mental model. For a single PostgreSQL container, both approaches work. Choose whichever feels more comfortable.

Common Mistakes and How to Fix Them

Several errors occur repeatedly when beginners first run PostgreSQL in Docker. Knowing what to look for saves time.

Forgetting the POSTGRES_PASSWORD Variable

The container exits immediately with an error. Diagnose it with:

docker logs postgres-local

The log contains a message similar to:

Error: Database is uninitialized and superuser password is not specified.
       You must specify POSTGRES_PASSWORD to a non-empty value for the
       superuser.

To fix it, remove the failed container and create a new one with the variable set:

docker rm postgres-local
docker run --name postgres-local -e POSTGRES_PASSWORD=secret -p 5432:5432 -d postgres:18

Host Port Already in Use

If port 5432 is already occupied on your host, docker run fails with:

Error starting userland proxy: listen tcp4 0.0.0.0:5432: bind: address already in use

You have two options. The first is to stop whatever program is using port 5432. On Linux and macOS, find the process with:

lsof -i :5432

On Windows, use:

netstat -ano | findstr :5432

The second option is to use a different host port:

docker run --name postgres-local -e POSTGRES_PASSWORD=secret -p 5433:5432 -d postgres:18

Then connect to localhost:5433 instead of localhost:5432.

Authentication Failure

If you see an error like:

FATAL: password authentication failed for user "postgres"

The password you typed does not match the POSTGRES_PASSWORD variable you set when creating the container. Double-check the exact spelling, including uppercase and lowercase letters. If you have forgotten the password, remove the container and volume, then start fresh:

docker rm -f postgres-local
docker volume rm postgres-data
docker run --name postgres-local -e POSTGRES_PASSWORD=newpassword -v postgres-data:/var/lib/postgresql/data -p 5432:5432 -d postgres:18

Data Disappeared After Removing a Container

If you removed a container without attaching a volume and then recreated it, your data is gone. This is expected behavior: containers are disposable, and only volumes persist.

Going forward, always attach a named volume to any database container whose data you care about. Development databases often do not need persistent storage, but it is safer to use a volume by default.

Volume Name Mismatch:

If you start a container with -v mydata:/var/lib/postgresql/data and later recreate it with -v otherdata:/var/lib/postgresql/data, PostgreSQL initializes a fresh database. The old data still exists in the mydata volume, but the new container does not see it.

Working with Multiple PostgreSQL Containers

Running multiple PostgreSQL containers simultaneously is common when you work on several projects or need different versions for testing.

Each container needs its own host port and its own name:

# First container for project A
docker run --name db-alpha \
  -e POSTGRES_PASSWORD=alpha123 \
  -e POSTGRES_DB=alpha_app \
  -p 5432:5432 \
  -v alpha-data:/var/lib/postgresql/data \
  -d postgres:18
# Second container for project B
docker run --name db-beta \
  -e POSTGRES_PASSWORD=beta123 \
  -e POSTGRES_DB=beta_app \
  -p 5433:5432 \
  -v beta-data:/var/lib/postgresql/data \
  -d postgres:17

The first container uses host port 5432 and PostgreSQL 18. The second uses host port 5433 and PostgreSQL 17. Both run side by side without interference because their host ports differ and their data volumes are separate.

When you connect to localhost:5432, you reach the first container. When you connect to localhost:5433, you reach the second.

To see all running containers at a glance:

docker ps

The output shows each container with its name, port mapping, and status:

CONTAINER ID   IMAGE        PORTS                    NAMES
1a2b3c4d5e6f   postgres:18  0.0.0.0:5432->5432/tcp   db-alpha
7f8e9d0c1b2a   postgres:17  0.0.0.0:5433->5432/tcp   db-beta

This isolation is one of the main reasons to use Docker for local development. You can experiment freely without worrying about conflicts between projects.

A Practical Workflow for Local Development

Bringing everything together, here is a typical workflow you will repeat throughout your Axum projects.

First, start a PostgreSQL container with a named volume:

docker run --name axum-db \
  -e POSTGRES_USER=axum \
  -e POSTGRES_PASSWORD=axumpassword \
  -e POSTGRES_DB=axum_app \
  -p 5432:5432 \
  -v axum-data:/var/lib/postgresql/data \
  -d postgres:18

Next, verify that the container is healthy:

docker exec axum-db pg_isready -U axum

You should see:

/var/run/postgresql:5432 - accepting connections

Now you can connect to the axum_app database from any PostgreSQL client, including the psql tool inside the container:

docker exec -it axum-db psql -U axum -d axum_app

When you are done working for the day, stop the container to free up memory:

docker stop axum-db

The next day, start it again:

docker start axum-db

All your data is still there, stored in the axum-data volume.

If you ever want a completely fresh start:

docker rm -f axum-db
docker volume rm axum-data

Then run the initial docker run command again to create a brand-new database.

Summary

Docker changes the way you think about local databases. Instead of installing PostgreSQL as a system service and accepting whatever state it accumulates, you treat the database as a disposable resource that you can start, stop, recreate, and discard at will.

The core pattern is simple: pull the official postgres image, run a container with environment variables that define the superuser credentials, publish a port so your host can connect, and attach a volume so your data survives container removal.

The environment variables are only read on first initialization, which means a stopped container resumes with the same credentials and data when you start it again. This matters when you are debugging authentication failures: changing the variables without resetting the volume has no effect.

Docker Compose gives you a declarative alternative when the command line becomes too verbose. A YAML file documents the entire setup, making it reproducible across machines and easy to extend with additional services later.

The database you have running in Docker is now ready to serve as the backend for an Axum application. When you build your first Axum project and connect it to PostgreSQL, the connection string will point to localhost:5432 with the credentials you defined here. You can start and stop the database independently of your application, which gives you a clean separation between infrastructure and code during development.