[英]Docker image not running, db error: django.db.utils.OperationalError could not translate host name "postgres" to address: Name or service not known
So I've managed to build my Docker image locally using docker-compose build
and I've pushed the image to my Docker Hub repository.因此,我设法使用
docker-compose build
在本地构建了我的 Docker 图像,并将该图像推送到我的 Docker Hub 存储库。
Now I'm trying to get it working on DigitalOcean so I can host it.现在我正试图让它在 DigitalOcean 上运行,以便我可以托管它。 I've pulled the correct version of the image and I am trying to run it with the following command:
我已经提取了正确版本的图像,并尝试使用以下命令运行它:
root@my-droplet:~# docker run --rm -it -p 8000:8000/tcp mycommand/myapp:1.1
(yes, 1.1) root@my-droplet:~# docker run --rm -it -p 8000:8000/tcp mycommand/myapp:1.1
(是的,1.1)
However I soon run into these two errors:但是我很快就遇到了这两个错误:
... File "/usr/local/lib/python3.8/dist-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.8/dist-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "postgres" to address: Name or service not known ```
... File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.8/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.8/dist-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known ```
This may be due to how I have divided my application (using docker-compose,yml
) into two services and have only pushed the image of the app since my previous post .这可能是由于我如何将我的应用程序(使用
docker-compose,yml
)划分为两个服务,并且自上一篇文章以来只推送了应用程序的图像。 Here is my docker-compose.yml
file:这是我的
docker-compose.yml
文件:
Here is my docker-compose.yml file:这是我的 docker-compose.yml 文件:
version: '3'
services:
db:
image: postgres
environment:
- POSTGRES_DB=postgres
- POSTGRES_USER=(adminname)
- POSTGRES_PASSWORD=(adminpassword)
- CLOUDINARY_URL=(cloudinarykey)
app:
build: .
ports:
- "8000:8000"
depends_on:
- db
Here is my Dockerfile:这是我的 Dockerfile:
FROM (MY FRIENDS ACCOUNT)/django-npm:latest
RUN mkdir usr/src/mprova
WORKDIR /usr/src/mprova
COPY frontend ./frontend
COPY backend ./backend
WORKDIR /usr/src/mprova/frontend
RUN npm install
RUN npm run build
WORKDIR /usr/src/mprova/backend
ENV DJANGO_PRODUCTION=True
RUN pip3 install -r requirements.txt
EXPOSE 8000
CMD python3 manage.py collectstatic && \
python3 manage.py makemigrations && \
python3 manage.py migrate && \
gunicorn mellon.wsgi --bind 0.0.0.0:8000
and here is a snippet of my settings.py
file:这是我的
settings.py
文件的片段:
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'admin',
'PASSWORD': '[THE PASSWORD]',
'HOST': 'db',
'PORT': 5432,
}
}
...
How can I fix this issue?我该如何解决这个问题? I've looked around but can't see what I'm doing wrong.
我环顾四周,但看不出我做错了什么。
From what I saw online, I added the following to my project, but it doesn't work either:根据我在网上看到的,我将以下内容添加到我的项目中,但它也不起作用:
Here is my base.py
(new file):这是我的
base.py
(新文件):
import psycopg2
conn = psycopg2.connect("dbname='postgres' user='admin' host='db' password='[THE PASSWORD]'")
Additions to Dockerfile
:添加到
Dockerfile
:
FROM (MY FRIENDS ACCOUNT)/django-npm:latest
RUN pip3 install psycopg2-binary
COPY base.py base.py
RUN python3 base.py
...
Yet the build fails due to this error:然而,由于这个错误,构建失败了:
Traceback (most recent call last): File "base.py", line 3, in <module> conn = psycopg2.connect("dbname='postgres' user='admin' host='db' password='[THE PASSWORD]'") File "/usr/local/lib/python3.8/dist-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "db" ([SOME-IP-ADDRESS]) and accepting TCP/IP connections on port 5432? ERROR: Service 'app' failed to build: The command '/bin/sh -c python3 base.py' returned a non-zero code: 1 me@My-MacBook-Pro-5 mellon %
I'm unsure as to what to try next but I feel like I am making a simple mistake.我不确定接下来要尝试什么,但我觉得我犯了一个简单的错误。 Why is the connection being refused at the moment?
为什么此时连接被拒绝?
When you launch a docker-compose.yml
file, Compose will automatically create a Docker.network for you and attach containers to it.当您启动
docker-compose.yml
文件时,Compose 会自动为您创建一个 Docker.network 并将容器附加到它。 Absent any specific networks:
declarations in the file, Compose will name the.network default
, and then most things Compose creates are prefixed with the current directory name.如果文件中没有任何特定的
networks:
声明,Compose 将命名为 .network default
,然后 Compose 创建的大多数内容都以当前目录名称为前缀。 This setup is described in more detail in Networking in Compose .此设置在 Compose 中的网络 中有更详细的描述。
docker run
doesn't look at the Compose settings at all, so anything you manually do with docker run
needs to replicate the settings docker-compose.yml
has or would automatically generate. docker run
根本不查看 Compose 设置,因此您使用docker run
手动执行的任何操作都需要复制docker-compose.yml
已经或将自动生成的设置。 To make a docker run
container connect to a Compose.network, you need to do something like:要使
docker run
容器连接到 Compose.network,您需要执行以下操作:
docker network ls # looking for somename_default
docker run \
--rm -it -p 8000:8000/tcp \
--net somename_default \ # <-- add this option
mycommand/myapp:1.1
(The specific error message could not translate host name "postgres" to address
hints at a Docker.networking setup issue: the database client container isn't on the same.network as the database server and so the hostname resolution fails. Contrast with a "connection refused" type error, which would suggest one container is finding the other but either the database isn't running yet or the port number is wrong.) (特定错误消息
could not translate host name "postgres" to address
Docker.networking 设置问题的提示:数据库客户端容器与数据库服务器不在同一个网络上,因此主机名解析失败。对比“连接被拒绝”类型错误,这表明一个容器正在寻找另一个容器,但数据库尚未运行或端口号错误。)
In your docker build
example, code in a Dockerfile can never connect to a database.在您的
docker build
示例中,Dockerfile 中的代码永远无法连接到数据库。 At a mechanical level, there's no way to attach it to a Docker.network as we did with docker run
.在机械层面上,无法像我们使用
docker run
那样将其附加到 Docker.network。 At a conceptual level, building an image produces a reusable artifact;在概念层面上,构建图像会产生可重用的工件; if I
docker push
the image to a registry and docker run
it on a different host, that won't have the database setup, or similarly if I delete and recreate the database container locally.如果我
docker push
送到注册表并docker run
它,则不会设置数据库,或者类似地,如果我在本地删除并重新创建数据库容器。
I am trying to run it with the following command: root@my-droplet:~#
我正在尝试使用以下命令运行它:root@my-droplet:~#
docker run --rm -it -p 8000:8000/tcp mycommand/myapp:1.1 (yes, 1.1)
docker 运行 --rm -it -p 8000:8000/tcp mycommand/myapp:1.1(是的,1.1)
Docker-compose allows to create a composition of several containers. Docker-compose 允许创建多个容器的组合。
Running the django container with docker run
defeats its purpose.使用
docker run
django 容器达不到目的。
What you want is running:你想要的是运行:
docker-compose build
docker-compose up
or in a single command:或者在一个命令中:
docker-compose up --build
Why is the connection being refused at the moment?
为什么此时连接被拒绝?
Maybe because that is not done at the right moment.也许是因为那不是在正确的时间完成的。
I am not a Django specialist but your second try looks ok while your django service misses the Dockerfile attribute in the compose declaration (typing error I assume).我不是 Django 专家,但您的第二次尝试看起来没问题,而您的 django 服务错过了撰写声明中的 Dockerfile 属性(我认为是输入错误)。
For your first try, that error:对于您的第一次尝试,该错误:
django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known ```
means that django uses "postgres" as host of the database.意味着 django 使用“postgres”作为数据库的主机。
But according to your compose, the database could be reached with a host named "db".但是根据您的撰写,可以使用名为“db”的主机访问数据库。 These don't match.
这些不匹配。
Regarding your second try that defines database properties, it looks fine and it also matches to what the official doc states :关于您定义数据库属性的第二次尝试,它看起来不错,并且也符合官方文档的说明:
In this section, you set up the database connection for Django.
在本节中,您将为 Django 设置数据库连接。
In your project directory, edit the composeexample/settings.py file.
在您的项目目录中,编辑 composeexample/settings.py 文件。
Replace the DATABASES =... with the following:
将 DATABASES =... 替换为以下内容:
settings.py
设置.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } These settings are determined by the postgres Docker image specified in docker-compose.yml.
For your second try, that error:对于您的第二次尝试,该错误:
conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "db" ([SOME-IP-ADDRESS]) and accepting
TCP/IP connections on port 5432?
may mean that the Postgres DB listener is not ready yet when Django tries to init the connection with.可能意味着当 Django 尝试初始化连接时,Postgres DB 侦听器尚未准备好。
That attributes of your compose: depends_on:
defines order of container start but doesn't wait for that the application behind the container be "ready".您的 compose:
depends_on:
定义容器启动的顺序,但不等待容器后面的应用程序“准备就绪”。
Here two way to addresse that kind of scenario:这里有两种方法可以解决这种情况:
For the first way, configure your django service with a CMD such as (not tried):对于第一种方式,使用 CMD 配置您的 django 服务,例如(未尝试):
app:
build: .
ports:
- "8000:8000"
depends_on:
- db
command: /bin/bash -c "sleep 30; python3 manage.py collectstatic && python3 manage.py makemigrations && python3 manage.py migrate && gunicorn mellon.wsgi --bind 0.0.0.0:8000 "
For the second way, try something like that:对于第二种方式,尝试这样的事情:
app:
build: .
ports:
- "8000:8000"
depends_on:
- db
restart: on-failure
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.