Docker中主机的localhost和Postgres之间的区别 [英] difference between localhost and postgres for host in docker
问题描述
我正在开发Django应用,并尝试在docker中运行它。我有一个到目前为止无法理解的问题。使用 docker-compose
运行应用程序时,当我使用 web
应用程序似乎无法连接到数据库时配置:
I am developing a django app and trying to run it inside docker. I have an issue that I could not understand so far. while running the app with docker-compose
, it seems that the web
app cannot connect to the database when i use these configurations:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'my_db',
'USER': 'my_user',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '5432',
}
但是一旦我将主机更改为 postgres
,它就会起作用。像这样
but once I change the host to postgres
, it works. like this
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'my_db',
'USER': 'my_user',
'PASSWORD': '',
'HOST': 'postgres',
'PORT': '5432',
}
是 postgres
和 localhost
之间的区别。一个在docker内部运行并且没有问题,而不是在我的mac上的开发环境中运行,另一个则相反。
what is the difference between postgres
and localhost
. One is running without and issue inside docker and not in development environment in my mac and the other one is the opposite.
# docker-compose.yml
version: '3'
services:
db:
image: postgres
expose:
- "5432"
web:
build: .
command: python3 manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
推荐答案
每个docker默认情况下,容器带有它自己的网络名称空间。该名称空间包括其自己的专用回送接口,即localhost。而且它们还连接到docker内部的网络,在那里它们具有自己的内部DNS条目,并且可以与同一网络上的其他容器进行通信。
Each docker container comes with it's own networking namespace by default. That namespace includes it's own private loopback interface, aka localhost. And they are also attached to networks inside of docker where they have their own internal DNS entry and can talk to other containers on that same network.
在内部运行应用程序时如果是具有网桥网络的容器,则localhost将指向该容器,而不是您正在运行的Docker主机。使用的主机名取决于您的情况:
When you run your application inside a container with a bridge network, localhost will point to the container, not the docker host you are running on. The hostname to use depends on your scenario:
- 要与其他容器通信,请使用DNS中的容器名称。
- 如果它是由docker-compose启动的,请使用服务名称通过DNS轮询与该服务中的一个容器进行对话。
- 如果它是在swarm模式下启动的,您可以使用那里的服务名称转到VIP,该VIP可以对提供该服务的所有容器进行负载均衡。
- 如果您需要与Docker主机本身进行对话,请使用docker主机的非环回IP地址。
- To talk to other containers, use the container name in DNS.
- If it's started by docker-compose, use the service name to talk to one of the containers in that service using DNS round robin.
- If it's started inside of swarm mode, you can use the service name there to go to a VIP that round robin load balances to all containers providing that service.
- And if you need to talk to the docker host itself, use a non-loopback IP address of the docker host.
这篇关于Docker中主机的localhost和Postgres之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!