How to access postgres database on host from docker container?
I have a docker file with a django project trying to use a database located on the host machine.
Now my Dockerfile:
FROM python:3-slim
ENV PYTHONUNBUFFERED 1
RUN mkdir /code.
WORKDIR /code
ADD . /code/
RUN pip install -r requirements.txt
RUN export dockerhost=$(docker-machine ip)
docker-compose.yml:
version: "2"
networks:
workernetwork:
webnetwork:
services:
static:
volumes:
- /static:/static
- /media:/media
image: alpine:latest
web:
build: .
command: bash -c "SECRET_KEY=temp_value python /code/manage.py collectstatic --noinput && python /code/manage.py migrate && /code/run_gunicorn.sh"
volumes:
- .:/code
volumes_from:
- static
env_file:
- secrets.env
ports:
- 443:443
networks:
- webnetwork
extra_hosts:
- "dockerhost:${dockerhost}"
DATABASES
in settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'revolution',
'USER': get_env_setting('POSTGRES_USER'),
'PASSWORD': get_env_setting('POSTGRES_PASSWORD'),
'HOST': 'dockerhost',
'PORT': 5432,
}
}
What am I doing wrong?
thanks for attention!
source to share
Finally, resolved with docker volume:
as the first one, create the volume:
docker volume create --name=coredb
Docker-compose.yml
version: "2"
services:
...
web:
build:
context: .
command: bash -c "python /code/manage.py collectstatic --noinput && python /code/manage.py migrate && /code/run_gunicorn.sh"
volumes:
- /static:/data/web/static
- /media:/data/web/media
- .:/code
env_file:
- ../.env
depends_on:
- db
db:
restart: always
image: postgres
env_file:
- ../.env
volumes:
- pgdata: /var/lib/postgresql/data
volumes:
pgdata:
external:
name: coredb
.env variables:
POSTGRES_DB={hidden}
POSTGRES_USER={hidden}
POSTGRES_PASSWORD={hidden}
Important: You need to create the database and user manually through docker exec -it backend_db_1 bash
and after this instructions before Install Django within a Virtual Environment
chapter
source to share
I had the same problem. The problem was that the connection was blocked between netwrok. I fixed it by creating a network named bridge:
docker network create \
--driver bridge \
--opt "com.docker.network.bridge.name"="docker_webnetwork" \
webnetwork
I am using UFW as my firewal. Therefore, connection to my created network is allowed to port postegres.
sudo ufw allow in on docker_webnetwork to any port 5432
Then you can use the web to connect to your postgresql master
To get the IP of the host, I add:
export DOCKERHOST=$(ip route | awk '/^default via /{print $3}')
in the service command that needs to access the database.
source to share