Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

django - difference between localhost and postgres for host in docker

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',
    }

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',
    }

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Docker Compose actually add the hostnames of all your linked containers to each other.

On you machine, the postgres database is actually running in localhost, that why you have the localhost hostname.

In Compose, it's running in the postgres container, with the hostname postgres, that's why you have the postgres hostname.

If you want, you can create an entry in your host file to redirect postgres to localhost, you will then just have to use postgres everywhere.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...