Deploy a Database
Step-by-step tutorial for deploying a PostgreSQL database with LoKO.
Overview
Section titled “Overview”This tutorial covers:
- Adding PostgreSQL to your environment
- Accessing the database
- Connecting from applications
- Managing data persistence
- Deploying additional tools (pgAdmin)
Time: 10 minutes
Prerequisites:
- LoKO installed
- Environment created (First Cluster)
Step 1: Add PostgreSQL
Section titled “Step 1: Add PostgreSQL”Add PostgreSQL to your configuration:
loko workloads add postgresOutput:
✓ Added postgres to loko.yaml State: enabled (not deployed)
Next steps: Deploy: loko workloads deploy postgres Disable: loko workloads disable postgresThis adds PostgreSQL to loko.yaml:
workloads: postgres: enabled: true namespace: loko-workloads storage: enabled: true size: 10Gi ports: - 5432Step 2: Deploy PostgreSQL
Section titled “Step 2: Deploy PostgreSQL”Deploy the workload:
loko workloads deploy postgresOutput:
Deploying workloads: postgres
Generated credentials: postgres: POSTGRES_USER: postgres POSTGRES_PASSWORD: 8x9YzA2bC3dE4fG POSTGRES_DB: postgres
Credentials saved to: .loko-secrets.txt
Deploying via helmfile...✓ postgres deployed successfully
Status: postgres: Running (1/1 pods ready) Endpoint: postgres.dev.me:5432What happened:
- Generated random password
- Created Kubernetes namespace
- Deployed PostgreSQL via Helm
- Created PersistentVolumeClaim (10Gi)
- Configured TCP routing through Traefik
- Updated DNS for
postgres.dev.me
Step 3: Verify Deployment
Section titled “Step 3: Verify Deployment”Check status:
loko statusOutput:
Environment: loko-dev-meCluster: Running
Workloads: postgres (loko-workloads) Status: Running Pods: 1/1 Endpoint: postgres.dev.me:5432 Storage: 10Gi (PVC: postgres-data)Check credentials:
cat .loko-secrets.txtOutput:
=== postgres ===POSTGRES_USER: postgresPOSTGRES_PASSWORD: 8x9YzA2bC3dE4fGPOSTGRES_DB: postgresStep 4: Connect to Database
Section titled “Step 4: Connect to Database”Using psql CLI
Section titled “Using psql CLI”# Get password from .loko-secrets.txtexport PGPASSWORD="8x9YzA2bC3dE4fG"
# Connectpsql -h postgres.dev.me -U postgres -d postgresInteractive session:
postgres=# SELECT version();postgres=# \l -- List databasespostgres=# \q -- QuitUsing DBeaver / DataGrip
Section titled “Using DBeaver / DataGrip”Connection Details:
- Host:
postgres.dev.me - Port:
5432 - Database:
postgres - User:
postgres - Password: (from
.loko-secrets.txt)
Using GUI Tool
Section titled “Using GUI Tool”Deploy pgAdmin:
loko workloads add pgadmin --nowAccess at: http://pgadmin.dev.me
Add Server:
- Right-click “Servers” → “Create” → “Server”
- General tab:
- Name: “LoKO PostgreSQL”
- Connection tab:
- Host:
postgres.dev.me - Port:
5432 - Username:
postgres - Password: (from
.loko-secrets.txt)
- Host:
- Click “Save”
Step 5: Create Database and Tables
Section titled “Step 5: Create Database and Tables”Connect and create a sample database:
-- Create databaseCREATE DATABASE myapp;
-- Connect to it\c myapp
-- Create tableCREATE TABLE users ( id SERIAL PRIMARY KEY, name VARCHAR(100), email VARCHAR(100) UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
-- Insert dataINSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com'), ('Bob', 'bob@example.com');
-- QuerySELECT * FROM users;Step 6: Connect from Application
Section titled “Step 6: Connect from Application”Python Application
Section titled “Python Application”install psycopg2:
pip install psycopg2-binaryconnect.py:
import psycopg2import os
# Read password from filewith open('.loko-secrets.txt') as f: for line in f: if 'POSTGRES_PASSWORD' in line: password = line.split(': ')[1].strip()
# Connectconn = psycopg2.connect( host="postgres.dev.me", port=5432, database="myapp", user="postgres", password=password)
# Querycur = conn.cursor()cur.execute("SELECT * FROM users")rows = cur.fetchall()
for row in rows: print(row)
cur.close()conn.close()Run:
python connect.pyGo Application
Section titled “Go Application”main.go:
package main
import ( "database/sql" "fmt" _ "github.com/lib/pq")
func main() { connStr := "host=postgres.dev.me port=5432 user=postgres password=8x9YzA2bC3dE4fG dbname=myapp sslmode=disable" db, err := sql.Open("postgres", connStr) if err != nil { panic(err) } defer db.Close()
rows, err := db.Query("SELECT * FROM users") if err != nil { panic(err) } defer rows.Close()
for rows.Next() { var id int var name, email string var createdAt string rows.Scan(&id, &name, &email, &createdAt) fmt.Printf("%d: %s <%s>\n", id, name, email) }}Node.js Application
Section titled “Node.js Application”install pg:
npm install pgapp.js:
const { Client } = require('pg')
const client = new Client({ host: 'postgres.dev.me', port: 5432, user: 'postgres', password: '8x9YzA2bC3dE4fG', // From .loko-secrets.txt database: 'myapp'})
client.connect()
client.query('SELECT * FROM users', (err, res) => { console.log(res.rows) client.end()})Step 7: Configure Custom Settings
Section titled “Step 7: Configure Custom Settings”Customize PostgreSQL settings in loko.yaml:
workloads: postgres: enabled: true storage: size: 20Gi # Increase storage values: settings: max_connections: "200" # Increase connections shared_buffers: "512MB" # Increase buffer work_mem: "4MB" maintenance_work_mem: "64MB"Apply changes:
loko workloads deploy postgres --forceStep 8: Data Persistence
Section titled “Step 8: Data Persistence”Verify Persistent Storage
Section titled “Verify Persistent Storage”Check PVC:
kubectl get pvc -n loko-workloadsOutput:
NAME STATUS VOLUME CAPACITY STORAGE CLASSpostgres-data Bound pvc-xxx 10Gi standardTest Persistence
Section titled “Test Persistence”- Insert data:
INSERT INTO users (name, email) VALUES ('Charlie', 'charlie@example.com');SELECT COUNT(*) FROM users; -- Should be 3- Recreate cluster:
loko env recreate- Deploy again:
loko workloads deploy postgres- Check data (should still exist):
SELECT COUNT(*) FROM users; -- Still 3Note: Data persists across cluster recreations because it’s stored in Docker volumes.
Step 9: Backup and Restore
Section titled “Step 9: Backup and Restore”Manual Backup
Section titled “Manual Backup”# Backup databasepg_dump -h postgres.dev.me -U postgres myapp > backup.sql
# Restore to new databasepsql -h postgres.dev.me -U postgres -d postgres -c "CREATE DATABASE myapp_restore"psql -h postgres.dev.me -U postgres myapp_restore < backup.sqlAutomated Backups
Section titled “Automated Backups”Use Kubernetes CronJob:
apiVersion: batch/v1kind: CronJobmetadata: name: postgres-backup namespace: loko-workloadsspec: schedule: "0 2 * * *" # Daily at 2 AM jobTemplate: spec: template: spec: containers: - name: backup image: postgres:15 command: - sh - -c - pg_dump -h postgres -U postgres myapp > /backup/backup-$(date +%Y%m%d).sql volumeMounts: - name: backup mountPath: /backup volumes: - name: backup hostPath: path: /tmp/postgres-backupsStep 10: Clean Up
Section titled “Step 10: Clean Up”Remove workload (keep data):
Section titled “Remove workload (keep data):”loko workloads disable postgres --nowRemove workload and data:
Section titled “Remove workload and data:”loko workloads remove postgres --nowThis deletes:
- Deployment
- Service
- PersistentVolumeClaim
- Secrets
Next Steps
Section titled “Next Steps”Try deploying other databases:
# MySQLloko workloads add mysql --now
# MongoDBloko workloads add mongodb --now
# Redis-compatible cacheloko workloads add valkey --nowSee Workload Catalog for all available workloads.
Troubleshooting
Section titled “Troubleshooting”Can’t connect to database
Section titled “Can’t connect to database”Check DNS:
ping postgres.dev.me # Should resolveCheck pod status:
kubectl get pods -n loko-workloadskubectl logs -n loko-workloads postgres-xxxCheck service:
kubectl get svc -n loko-workloadsPassword doesn’t work
Section titled “Password doesn’t work”Regenerate secrets:
loko workloads remove postgres --nowrm .loko-secrets.txtloko workloads add postgres --nowStorage full
Section titled “Storage full”Increase size:
workloads: postgres: storage: size: 50Gi # Increase from 10GiRedeploy:
loko workloads deploy postgres --forceSee Also
Section titled “See Also”- Workload Management - Complete workload guide
- Workload Catalog - All available workloads
- Custom Workload Tutorial - Deploy custom applications
- First Cluster Tutorial - Getting started