Deploy

With the image in the registry, it’s time to run it. The application needs:

  • A PersistentVolumeClaim: storage for the SQLite database and uploaded images, which survives restarts.
  • A ConfigMap for ordinary settings, and a Secret for passwords and keys. Both become the application’s environment variables, so config/settings.py picks them up without any changes.
  • A Deployment, which runs the container and keeps it running.
  • A Service, which gives the application a stable address inside the cluster.
  • A Route, which makes it available outside the cluster, over HTTPS.

The YAML for each is in the example code’s openshift directory.

Storage#

openshift/pvc.yamlyaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: example-for-you-data
  labels:
    app: example-for-you
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi

ReadWriteOnce means the volume can be used by one node at a time, which is what most storage provides, and suits SQLite. OpenShift Local provides storage automatically.

Configuration#

Settings that aren’t secret go in a ConfigMap:

openshift/configmap.yamlyaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: example-for-you-config
  labels:
    app: example-for-you
data:
  CONF_MAIN_DOMAIN: "https://example-for-you-example-for-you.apps-crc.testing"
  CONF_ENABLE_APIS: "false"
  CONF_MAIL_DEV_MODE: "true"
  CONF_MAIL_SERVER: "smtp.example.com"
  CONF_MAIL_PORT: "587"
  CONF_MAIL_FROM: "noreply@exampleforyou.net"
  CONF_MAIL_CONTACT_TO: "hello@exampleforyou.net"

CONF_MAIN_DOMAIN is the address the Route will give the application, used in links in emails. On OpenShift Local, a Route’s address is <name>-<project>.apps-crc.testing. All values in a ConfigMap are strings, hence the quotes.

Secrets go in a Secret. Rather than writing them in YAML (where they’d be easy to commit by mistake), create the Secret from an env file. The example code includes a template:

openshift/secrets.env.exampletext
# Copy to secrets.env, fill in, and create the secret with:
#   oc create secret generic example-for-you-secrets --from-env-file=openshift/secrets.env
# Never commit secrets.env.
CONF_AUTH_SECRET_KEY=generate-with-python-c-import-secrets-print-secrets-token-hex-32
CONF_MAIL_USERNAME=
CONF_MAIL_PASSWORD=
CONF_STRIPE_SECRET_KEY=
CONF_STRIPE_PRICE=
CONF_STRIPE_WEBHOOK_SECRET=

Copy it to openshift/secrets.env (which is in .gitignore), fill it in, and create the Secret:

cp openshift/secrets.env.example openshift/secrets.env
oc create secret generic example-for-you-secrets --from-env-file=openshift/secrets.env

CONF_AUTH_SECRET_KEY must be set: generate one with python -c "import secrets; print(secrets.token_hex(32))".

note

Kubernetes Secrets are only base64-encoded, not encrypted, so anyone who can read Secrets in the project can read them. OpenShift restricts who can, and clusters can encrypt them at rest. For more, look at tools such as the External Secrets Operator or Sealed Secrets.

Deployment#

openshift/deployment.yamlyaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: example-for-you
  labels:
    app: example-for-you
spec:
  # SQLite and the uploads live on a ReadWriteOnce volume, so run one copy,
  # and stop the old pod before starting a new one
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: example-for-you
  template:
    metadata:
      labels:
        app: example-for-you
    spec:
      containers:
        - name: example-for-you
          image: image-registry.openshift-image-registry.svc:5000/example-for-you/example-for-you:1.0.0
          ports:
            - name: http
              containerPort: 8080
          envFrom:
            - configMapRef:
                name: example-for-you-config
            - secretRef:
                name: example-for-you-secrets
          volumeMounts:
            - name: data
              mountPath: /opt/app-root/src/mnt
          readinessProbe:
            httpGet:
              path: /api/v1/health
              port: http
            periodSeconds: 10
          livenessProbe:
            httpGet:
              path: /api/v1/health
              port: http
            initialDelaySeconds: 15
            periodSeconds: 20
          resources:
            requests:
              cpu: 100m
              memory: 256Mi
            limits:
              memory: 512Mi
          securityContext:
            allowPrivilegeEscalation: false
            runAsNonRoot: true
            capabilities:
              drop: ["ALL"]
            seccompProfile:
              type: RuntimeDefault
      volumes:
        - name: data
          persistentVolumeClaim:
            claimName: example-for-you-data

There’s quite a lot here, so taking it a piece at a time:

  • replicas: 1 and strategy: Recreate: the SQLite database and uploads are on one ReadWriteOnce volume, so only one copy of the application can run, and when updating, the old pod must stop before the new one starts.
  • image: the image in OpenShift’s internal registry, from the previous section.
  • envFrom turns every key in the ConfigMap and the Secret into an environment variable.
  • volumeMounts mounts the storage at mnt, where the application expects its database and uploads.
  • readinessProbe: OpenShift only sends traffic to the pod once /api/v1/health answers. livenessProbe: if it stops answering, OpenShift restarts the container. This is what the health API from the very first section is for.
  • resources: requests is what the pod is guaranteed (a tenth of a CPU, and 256 MiB of memory); limits caps the memory at 512 MiB.
  • securityContext asks for no extra privileges. OpenShift’s default security policy, restricted-v2, requires these settings; spelling them out avoids warnings, and means the Deployment also works on other Kubernetes platforms with the same rules.

There’s no runAsUser: OpenShift chooses the random user id, which is why the image was built to allow it.

Service and Route#

openshift/service.yamlyaml
apiVersion: v1
kind: Service
metadata:
  name: example-for-you
  labels:
    app: example-for-you
spec:
  selector:
    app: example-for-you
  ports:
    - name: http
      port: 8080
      targetPort: http
openshift/route.yamlyaml
apiVersion: route.openshift.io/v1
kind: Route
metadata:
  name: example-for-you
  labels:
    app: example-for-you
spec:
  to:
    kind: Service
    name: example-for-you
  port:
    targetPort: http
  tls:
    termination: edge
    insecureEdgeTerminationPolicy: Redirect

The Service finds the application’s pods by their app: example-for-you label. The Route publishes the Service through OpenShift’s router. termination: edge means the router handles HTTPS, using the cluster’s certificate, and talks plain HTTP to the application; insecureEdgeTerminationPolicy: Redirect sends any http:// requests to https://. No host is given, so OpenShift chooses one.

Deploy#

With the Secret created, apply everything else:

oc apply -f openshift/pvc.yaml -f openshift/configmap.yaml -f openshift/deployment.yaml \
  -f openshift/service.yaml -f openshift/route.yaml

Watch the pod start:

oc get pods --watch
NAME                               READY   STATUS              RESTARTS   AGE
example-for-you-6c9d8b7f5d-x2k4p   0/1     ContainerCreating   0          3s
example-for-you-6c9d8b7f5d-x2k4p   0/1     Running             0          8s
example-for-you-6c9d8b7f5d-x2k4p   1/1     Running             0          15s

1/1 means the readiness probe has passed. Find the Route’s address:

oc get route example-for-you -o jsonpath='{.spec.host}'
example-for-you-example-for-you.apps-crc.testing

And open it in a browser, with https://. (OpenShift Local’s certificate is self-signed, so the browser will warn you.) If the address differs from CONF_MAIN_DOMAIN in the ConfigMap, update the ConfigMap, and restart the application to pick it up:

oc rollout restart deployment/example-for-you

Day to day#

See the application’s log output:

oc logs deployment/example-for-you

Create the first administrator, by running the script from the Authentication section in the running container:

oc exec -it deployment/example-for-you -- python -m db.create_user admin@example.com Ada Admin --author --superuser

Deploy a new version: build and push the image with a new tag, then point the Deployment at it:

oc set image deployment/example-for-you example-for-you=image-registry.openshift-image-registry.svc:5000/example-for-you/example-for-you:1.0.1

(Or change the tag in deployment.yaml and oc apply it, which keeps the file in step.) OpenShift stops the old pod, starts the new one, and the new version’s database migrations run as it starts. If something goes wrong, go back to the previous version:

oc rollout undo deployment/example-for-you

The web console shows all of this too: switch to the Developer perspective and open Topology.

Growing beyond one pod#

One pod with SQLite is plenty for a personal site or a blog. To run several copies of the application, for more capacity or so there’s no downtime during updates:

  • Move the database to PostgreSQL, running on OpenShift or as a managed service, by setting CONF_DATABASE_URL in the Secret (see the PostgreSQL part of the Databases section).
  • Store uploads somewhere every pod can reach, such as a ReadWriteMany volume or object storage.
  • Run the database migrations as a separate step, rather than in start.sh, so pods don’t run them at the same time.
  • Switch the Deployment back to the default RollingUpdate strategy, and increase replicas.
What was tested

While writing this guide, these files were run with podman kube play, which runs Kubernetes Deployments, PersistentVolumeClaims, ConfigMaps and Secrets locally with Podman: the settings reached the application, the volume was mounted, and the security settings applied. The Service and Route weren’t tested this way, as they need a real cluster.