无法让 Django 在 k8s 中与 Postgres 交谈



我在minikube中部署了一个简单的Django应用程序。它有两个容器,一个用于Django应用程序,一个用于postgres db。它可以与docker-compose一起工作,但不能在minikube k8s集群中工作。当我打开一个终端到集装箱并ping服务时,它没有成功。我不知道是什么原因导致了这个通信错误。

这是一个基本的应用程序,只有一个登录页面,用于登录或注册。登录后,您可以创建一些笔记。在我部署到minikube之后,我能够访问127.0.0.1:8000,但是当我输入注册信息时,它给出了下面的错误。显然,它不能在数据库中存储数据。

django项目settings.py中的database部分:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'db',
'PORT': '5432',
}
}

为应用构建镜像的Dockerfile:

FROM python:2.7
WORKDIR /notejam
COPY ./ ./
RUN pip install -r requirements.txt
EXPOSE 8000
CMD python manage.py runserver 0.0.0.0:8000

部署文件:

apiVersion: apps/v1
kind: Deployment
metadata:
name: notejam-deployment
labels: 
app: notejam-app
spec:
selector:
matchLabels:
app: notejam-app
template:
metadata:
labels:
app: notejam-app
spec:
volumes:
- name: postgres-pvc
persistentVolumeClaim:
claimName: postgres-pvc
containers:
- name: notejam
image: notejam_k8s
imagePullPolicy: Never
resources:
limits:
memory: "128Mi"
cpu: "500m"
ports:
- containerPort: 8000
- name: postgres-db
image: postgres
imagePullPolicy: Never
ports:
- containerPort: 5432
resources:
limits:
memory: "128Mi"
cpu: "500m"
env:
- name: POSTGRES_USERNAME
valueFrom:
configMapKeyRef:
name: postgres-configmap
key: postgres-username
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: postgres-secret
key: postgres-password
- name: POSTGRES_DB
valueFrom:
configMapKeyRef:
name: postgres-configmap
key: postgres-db
volumeMounts:
- mountPath: /notejam-db
name: postgres-pvc
---
apiVersion: v1
kind: Service
metadata:
name: db
spec:
selector:
app: notejam-app
ports:
- port: 5432
targetPort: 5432
---
apiVersion: v1
kind: Service
metadata:
name: notejam-external-service
spec:
selector:
app: notejam-app
type: LoadBalancer
ports:
- protocol: TCP 
port: 8000
targetPort: 8000

错误:

OperationalError at /signup/
could not connect to server: Connection timed out
Is the server running on host "db" (10.96.150.207) and accepting
TCP/IP connections on port 5432?
Request Method:     POST
Request URL:    http://127.0.0.1:8000/signup/
Django Version:     1.6.5
Exception Type:     OperationalError
Exception Value:    
could not connect to server: Connection timed out
Is the server running on host "db" (10.96.150.207) and accepting
TCP/IP connections on port 5432?
Exception Location:     /usr/local/lib/python2.7/site-packages/psycopg2/__init__.py in connect, line 127
Python Executable:  /usr/local/bin/python
Python Version:     2.7.18
Python Path:    
['/notejam',
'/usr/local/lib/python27.zip',
'/usr/local/lib/python2.7',
'/usr/local/lib/python2.7/plat-linux2',
'/usr/local/lib/python2.7/lib-tk',
'/usr/local/lib/python2.7/lib-old',
'/usr/local/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/site-packages']
Server time:    Thu, 26 Aug 2021 00:40:58 +0300

您正在尝试将postgres作为同一pod中的辅助容器运行。它应该是自己的部署和服务。多容器pod不像docker compose:)

最新更新