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
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:
- Create a ConfigMap containing the SQL initialization script^[400-devops__06-Kubernetes__k8s-ithelp__Day18__README.md].
- Mount the ConfigMap to the
/docker-entrypoint-initdb.dpath in the container using avolumeMount^[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.dto ensure the ConfigMap was mounted correctly^[400-devops__06-Kubernetes__k8s-ithelp__Day18__README.md]. - Check database: Use the
psqlCLI 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]
-
This paragraph interprets the source material's statement that separating configuration "lowers code coupling". ↩