Skip to content

PostgreSQL container initialization in Kubernetes

In Kubernetes, initializing a PostgreSQL container typically involves injecting environment variables for connection configuration and mounting initialization scripts to set up the database schema on startup^[400-devops__06-Kubernetes__k8s-ithelp__Day18__README.md]. These configurations are managed using ConfigMap resources, which decouple configuration artifacts from image content1.^[400-devops__06-Kubernetes__k8s-ithelp__Day18__README.md]

Configuration via Environment Variables

PostgreSQL containers, such as the official postgres image, allow configuration through environment variables. In a Pod definition, these can be injected using the valueFrom and configMapKeyRef fields^[400-devops__06-Kubernetes__k8s-ithelp__Day18__README.md].

For example, to set the user and password:

env:
  - name: POSTGRES_USER
    valueFrom:
      configMapKeyRef:
        name: initdb-kv-yaml
        key: PG_USER
  - name: POSTGRES_PASSWORD
    valueFrom:
      configMapKeyRef:
        name: initdb-kv-yaml
        key: PG_PASSWORD
This method enables the same container image to be deployed across different environments (e.g., Development, Production) simply by changing the attached ConfigMap^[400-devops__06-Kubernetes__k8s-ithelp__Day18__README.md].

Schema Initialization

Standard PostgreSQL Docker images support automatic execution of .sql, .sql.gz, and .sh scripts found in the /docker-entrypoint-initdb.d directory^[400-devops__06-Kubernetes__k8s-ithelp__Day18__README.md]. To utilize this in Kubernetes:

  1. Create a ConfigMap containing the SQL initialization script^[400-devops__06-Kubernetes__k8s-ithelp__Day18__README.md].
  2. Mount the ConfigMap to the /docker-entrypoint-initdb.d path in the container using a volumeMount^[400-devops__06-Kubernetes__k8s-ithelp__Day18__README.md].

Example configuration:

volumeMounts:
  - mountPath: /docker-entrypoint-initdb.d
    name: initdb
volumes:
  - name: initdb
    [ConfigMap](<./configmap.md>):
      name: initdb

Once the container starts, the SQL script is executed automatically, creating the necessary tables and schemas^[400-devops__06-Kubernetes__k8s-ithelp__Day18__README.md].

Verification

After initialization, the changes can be verified by accessing the running container^[400-devops__06-Kubernetes__k8s-ithelp__Day18__README.md].

  • Check scripts: List or read files in /docker-entrypoint-initdb.d to ensure the ConfigMap was mounted correctly^[400-devops__06-Kubernetes__k8s-ithelp__Day18__README.md].
  • Check database: Use the psql CLI to log in using the credentials defined in the ConfigMap and verify tables exist^[400-devops__06-Kubernetes__k8s-ithelp__Day18__README.md].

Sources

^[400-devops__06-Kubernetes__k8s-ithelp__Day18__README.md]


  1. This paragraph interprets the source material's statement that separating configuration "lowers code coupling".