Database Deployment
- Docker & Kubernetes course
- Intermediate
- Lesson 68/82
- 4 min
Write a Deployment and Service for the database.
The database Deployment
The database takes its password from a Secret and keeps its data in a volume. In this project, for simplicity, we use a single-replica Deployment; in production, a StatefulSet, which provides persistent storage and a stable identity, is preferred for databases (in the advanced section):
apiVersion: apps/v1
kind: Deployment
metadata:
name: db
namespace: magaza
spec:
replicas: 1
selector:
matchLabels: {app: db}
template:
metadata:
labels: {app: db}
spec:
containers:
- name: postgres
image: postgres:16
envFrom:
- secretRef:
name: db-gizli
ports:
- containerPort: 5432The database service and secret
The API connects to the database by the name db; this needs a ClusterIP Service with the same name. The password is put in the Secret with a command and isn't added to the repository as YAML:
kubectl create secret generic db-gizli -n magaza \
--from-literal=POSTGRES_PASSWORD="$DB_PAROLA" --from-literal=POSTGRES_DB=magaza
apiVersion: v1
kind: Service
metadata:
name: db
namespace: magaza
spec:
selector:
app: db
ports:
- port: 5432Practice The database service
Write a Service YAML: name db, namespace magaza; selector app: db; port 5432.
Starter code
# buraya yazSample solution
apiVersion: v1
kind: Service
metadata:
name: db
namespace: magaza
spec:
selector:
app: db
ports:
- port: 5432Expected output
service/db created
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is the database Deployment's replica count 1?
- It's cheaper
- A Service sees only one pod
- Several PostgreSQL copies can't write the same data; replication needs separate setup Correct answer
- Kubernetes doesn't allow it
Explanation: Database replicas are set up with their own replication protocols (e.g. an operator).
2 Make all keys of the Secret environment variables.
envFrom:
- ____:
name: db-gizli
envFrom:
- secretRef:
name: db-gizli
Explanation: secretRef under envFrom loads all keys.
3 Match.
| Term | Meaning |
|---|---|
db-gizli |
Password Secret |
Service db |
DNS name db |
replicas: 1 |
Single writer |
StatefulSet |
Production database |