在Kubernetes集群中配置Django连接PostgreSQL的HOST参数
Hey there! Let's break down your problems step by step and fix them one by one:
In Kubernetes, pods within the same namespace can communicate directly using the name of the PostgreSQL Service you've created. Here's how to set this up properly:
Update settings.py to use environment variables
Instead of hardcoding credentials (which is a security risk), pull all database config from environment variables. This also makes your setup flexible across environments:
import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent if os.getenv('ENVIRONMENT', 'development') == 'development': print('Development - Using "SQLITE3" Database') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } else: print('Production - Using "POSTGRESQL" Database') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), # This will be your PostgreSQL Service name 'PORT': os.getenv('DB_PORT', '5432'), # Default PostgreSQL port } }
Pass environment variables to your Django pod in Kubernetes
In your Django Deployment manifest, add these env vars (pull sensitive data from Secrets you've already created):
spec: containers: - name: django-app image: your-dockerhub-image:tag env: - name: ENVIRONMENT value: "production" - name: DB_NAME value: "agent_technologies_db" - name: DB_USER valueFrom: secretKeyRef: name: postgres-secret # Name of your PostgreSQL Secret key: username - name: DB_PASSWORD valueFrom: secretKeyRef: name: postgres-secret key: password - name: DB_HOST value: "postgres-service" # Replace with your PostgreSQL Service name - name: DB_PORT value: "5432"
Your current DB env var works, but using an ENVIRONMENT variable makes your config more explicit and scalable. Here's how to adapt it:
- For local development: No need to set any env vars (defaults to
developmentand uses SQLite) - For production (Kubernetes): Set
ENVIRONMENT=productionas shown above - Bonus: You can split settings into separate files (
settings/dev.py,settings/prod.py) and useDJANGO_SETTINGS_MODULEto switch between them, which is a common Django best practice.
The main issue here is likely using Django's runserver (a development server) in production. It's not designed for stability or performance, and by default binds only to 127.0.0.1 (which isn't accessible outside the pod). Here's the fix:
Switch to a production WSGI server (Gunicorn)
First, add gunicorn to your requirements.txt:
gunicorn>=20.1.0 # ... your other dependencies
Update your Dockerfile
Install Gunicorn and set a production-ready command:
FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /agent-technologies WORKDIR /agent-technologies COPY . /agent-technologies RUN pip install -r requirements.txt EXPOSE 8000 # Use Gunicorn instead of runserver CMD ["gunicorn", "--bind", "0.0.0.0:8000", "agents.config.settings.wsgi:application"]
Add database migrations (critical for production)
Before your app starts, you need to run Django migrations. Add an initContainer to your Deployment to handle this:
spec: initContainers: - name: migrate-db image: your-dockerhub-image:tag command: ["python", "src/manage.py", "migrate"] env: # Reuse the same env vars as your main Django container - name: ENVIRONMENT value: "production" - name: DB_NAME value: "agent_technologies_db" - name: DB_USER valueFrom: secretKeyRef: name: postgres-secret key: username - name: DB_PASSWORD valueFrom: secretKeyRef: name: postgres-secret key: password - name: DB_HOST value: "postgres-service" - name: DB_PORT value: "5432" containers: # ... your main Django container config
Debug further if crashes persist
If pods still crash, check the logs to get the exact error:
kubectl logs <your-django-pod-name>
Common issues to look for:
- PostgreSQL service isn't running or accessible
- Secret values are incorrect
- Missing dependencies in your Docker image
- File permission issues in the pod
内容的提问来源于stack exchange,提问作者Stefan Radonjic

