Skip to content

Docker · Technical

PostgreSQL Tutorial with Docker

Get your database running with Docker in minutes: a programming environment ready to go, without cluttering your hard drive!

In 2026, containerising critical infrastructure is no longer a cutting-edge option. It is a mandatory engineering standard for any organisation that wants to scale. Running a PostgreSQL instance with Docker is the most efficient and reproducible way to manage a relational database engine without compromising the integrity of the host operating system. It removes "dependency hell" at the root and makes the development environment an exact replica of production, which cuts the risks that come from configuration mismatches in critical deployments.

From a CTO's point of view, using Docker to manage PostgreSQL does more than simplify provisioning. It also streamlines the company's 2025 technology stack and gives full portability between cloud providers and on-premise servers. In this tutorial we break down the architecture needed to run PostgreSQL to industrial standards, with data persistence, security and operational efficiency as the priorities.

Why PostgreSQL and Docker in the Modern B2B Stack

PostgreSQL has become the relational database engine of choice for business applications, thanks to its strict compliance with the SQL standard and its robustness when handling complex transactions. Combined with Docker, it gives us full process isolation. Docker is not a traditional virtual machine: it is an operating-system-level virtualisation platform that uses containers to package software with all its dependencies.

For companies in Mallorca and start-ups across the Balearic ecosystem, where agility and time to market make the difference, Docker lets a senior developer set up a complete data infrastructure in a matter of seconds. That matters a great deal in custom software development projects, where the database has to work alongside complex microservices.

Infrastructure Requirements for Postgres with Docker

For a professional deployment in 2026, the requirements have moved on. Having "some spare capacity" is no longer enough; we need architectures that support virtualisation natively:

  1. Operating systems: Docker Desktop works well on Windows 11/12 (via WSL2) and macOS (Apple Silicon), but for server environments we strongly recommend Ubuntu (see our Introduction to Ubuntu) or Debian. They offer finer-grained resource management and noticeably lower disk I/O latency, which is critical for PostgreSQL performance.
  2. CPU architecture: With ARM processors on the rise in the cloud (AWS Graviton, Ampere on GCP), make sure you use multi-architecture images. The official PostgreSQL image on Docker Hub supports both x86_64 and arm64.
  3. Docker Compose: This is the essential local orchestration tool. In production we might use Kubernetes, but for development and continuous integration environments Docker Compose is the de facto standard. You can go deeper in our Docker Tutorial.

Deploying Postgres with Docker Compose (2026 Standard)

To start a PostgreSQL instance with every guarantee of persistence and configuration, we will use a docker-compose.yml file. This declarative approach lets you version your infrastructure as code (IaC), which makes collaboration easy with Git (see our Git Tutorial).

Create a directory for your project, for example ~/infra/postgres-data, and define the following file:

services:
  database:
    image: postgres:16-alpine
    container_name: arteco-postgres-prod
    restart: always
    environment:
      POSTGRES_USER: admin_user
      POSTGRES_PASSWORD: your_ultra_secure_password_2026
      POSTGRES_DB: enterprise_db
    ports:
      - "5432:5432"
    volumes:
      - ./postgres_data:​/var/lib/postgresql/data
      - ./init-scripts:​/docker-entrypoint-initdb.d
    networks:
      - backend-network
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U admin_user -d enterprise_db"]
      interval: 10s
      timeout: 5s
      retries: 5

networks:
  backend-network:
    driver: bridge

volumes:
  postgres_data:

Technical Breakdown of the Configuration:

  • Image (postgres:16-alpine): We use the alpine variant to keep the image small and reduce the attack surface. A lighter image means faster deployments and lower resource consumption on your agile cloud platform.
  • Data persistence: The ./postgres_data:/var/lib/postgresql/data mapping is the most critical point. Docker containers are ephemeral by nature; without this volume, any container restart would wipe out all your data. Mapping it to a local directory guarantees that the data survives.
  • Automatic initialisation: The ./init-scripts:/docker-entrypoint-initdb.d volume runs SQL or shell scripts the first time the container starts. It is ideal for creating schemas automatically or loading seed data in software integration tests.
  • Healthcheck: Essential in microservice architectures. It lets other services (such as an API built with Spring Boot) wait until the database is genuinely ready before trying to connect.

To run this infrastructure, move to the file's directory and run:

docker compose up -d

The -d (detached) option starts the services in the background. The first time, Docker will download the image layers from the official registry, set up the virtual network and mount the data volumes.

Verifying and Troubleshooting the Service

Once it is running, we need to check that the PostgreSQL engine is working properly and accepting connections. The main command for inspecting running containers is:

docker ps

You should see output similar to this, confirming that the status is Up and that the healthcheck has turned healthy:

CONTAINER ID   IMAGE                STATUS                     PORTS                    NAMES
a1b2c3d4e5f6   postgres:16-alpine   Up 2 minutes (healthy)    0.0.0.0:5432->5432/tcp   arteco-postgres-prod

If the container does not start, the first step is to check the engine logs for errors in the environment variables or file permissions:

docker logs arteco-postgres-prod

Professional PostgreSQL Management with External Clients

To work with the database visually, we recommend tools such as DBeaver or pgAdmin. Because port 5432 is mapped to the host, you connect from your local machine by pointing at localhost.

Suggested connection parameters:

  • Host: localhost
  • Port: 5432
  • Database: enterprise_db
  • User: admin_user
  • Password: your_ultra_secure_password_2026

If you are building business applications, you will probably need to connect this database to other technologies. For example, if you work with Java, have a look at our Migration to Spring Cloud and PostgreSQL project to see how to manage efficient connection pools with HikariCP.

Advanced User and Privilege Management

In a corporate environment, letting applications use the administrator account is a serious vulnerability. Following the principle of least privilege, we should create a dedicated user for each service.

To run SQL commands directly inside the container, use:

docker exec -it arteco-postgres-prod psql -U admin_user -d enterprise_db

Creating an application user:

-- Create the user with an encrypted password
CREATE USER app_service_user WITH ENCRYPTED PASSWORD 'service_secret_password';

-- Create a dedicated database for the service
CREATE DATABASE service_catalog_db;

-- Grant limited privileges
GRANT ALL PRIVILEGES ON DATABASE service_catalog_db TO app_service_user;

It is important to understand how granular permissions are in PostgreSQL. You can grant read-only access (SELECT) to data analysis tools, or full DML permissions to backend services. To master these statements, we recommend our SQL Tutorial.

Security and Hardening in Container Environments

Running PostgreSQL in Docker calls for extra layers of security that basic tutorials often skip. For a production environment, bear the following in mind:

  1. Secrets management: Never leave plain-text passwords in your docker-compose.yml file. Use .env files (excluded from Git) or, better still, Docker Secrets or Vault to inject credentials securely.
  2. Non-root user: By default, many containers run as root. Configure your image so that the PostgreSQL process runs under an unprivileged UID, limiting the damage in the event of a "container breakout".
  3. Network configuration: Do not expose port 5432 to the outside world (0.0.0.0). Restrict access with Docker's firewall, or bind the port to the loopback interface only (127.0.0.1:5432:5432) if only the local application needs access.
  4. Data encryption: For sensitive sectors in the Balearics (such as yachting or hospitality), it is vital to consider encrypting volumes at rest and using SSL/TLS connections for traffic between the application and the database. This is a core part of a secure development methodology.

Performance Optimisation and FinOps (Scaling in the Balearics)

Efficient use of resources is a priority for any company running its infrastructure in the cloud. From a FinOps perspective in the Balearics, tuning the database can mean significant savings on the monthly AWS or Azure bill.

Memory Tuning (Shared Buffers)

PostgreSQL in Docker ships with a conservative configuration. To make the most of modern hardware, adjust parameters such as shared_buffers (25% of available RAM is the usual recommendation) and work_mem. You can inject a custom configuration file:

volumes:
  - .​/my-postgres.conf:​/etc/postgresql/postgresql.conf
command: ["postgres", "-c", "config_file=/etc/postgresql/postgresql.conf"]

Monitoring and Maintenance

Running PostgreSQL without monitoring is flying blind. Use extensions such as pg_stat_statements to spot slow queries that may be hurting your digital marketing strategy through excessive latency on your website.

For agile development cycles, we also strongly recommend Testcontainers with Spring Boot. This technology spins up temporary PostgreSQL instances in Docker while your unit tests run, so your code is validated against a real database rather than an in-memory stand-in (H2), which prevents SQL compatibility errors in production.

Conclusion and Next Steps

Docker has changed the way we deploy data infrastructure, making PostgreSQL more accessible, more secure and easier to maintain. From isolated development environments to orchestrating distributed databases, the possibilities are huge. If you have already mastered PostgreSQL, the logical next step is to explore other data engines under the same approach, such as MySQL (see our MySQL Tutorial with Docker), to understand the operational differences between the two giants.

At Arteco Consulting, we help companies in the Balearics modernise their core technology through containerisation and the optimisation of their data infrastructure. If your organisation needs technology consulting to migrate legacy systems or design high-availability architectures, our team of B2B software development experts is ready to support you through this digital transformation.

Running PostgreSQL professionally is the foundation on which scalable, secure applications are built. Do not settle for local installations that clutter your operating system; embrace the container standard and raise the quality of your software engineering.


Using PostgreSQL or Docker in your company? At Arteco we help you scale your data architecture: cloud environments, high availability and zero-downtime migrations. Talk to a specialist →

Ramón Arnau Gómez

Ramón Arnau Gómez

Director de Arteco

Programador Java desde 2003. Ingeniero Informático (UIB), Máster en Tecnologías de la Información (UIB), Máster en Administración y Dirección de Empresas (UAX). Arquitecto Java

More articles by Ramón