In one folder I have 3 files: base.py, Dockerfile and docker-compose.yml.
base.py:
import psycopg2 conn = psycopg2.connect("dbname='base123' user='postgres' host='db' password='pw1234'") Dockerfile:
FROM ubuntu:16.04 RUN apt-get update RUN apt-get -y install python-pip RUN apt-get update RUN pip install --upgrade pip RUN pip install psycopg2-binary COPY base.py base.py RUN python base.py docker-compose.yml:
version: '3' services: db: image: 'postgres:latest' expose: - "5432" environment: POSTGRES_PASSWORD: pw1234 POSTGRES_DB: base123 aprrka: build: . depends_on: - db After I ran docker-compose up, I got the following error:
Traceback (most recent call last): File "base.py", line 5, in <module> conn = psycopg2.connect("dbname='base123' user='postgres' host='db' password='pw1234'") File "/usr/local/lib/python2.7/dist-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known ERROR: Service 'aprrka' failed to build: The command '/bin/sh -c python base.py' returned a non-zero code: 1 I don't know why I have this error. I exposed port 5432. By default Compose sets up a single network for app. Each service joins the default network, I think that my app with postgres should work together. Did I write incorrect docker-compose.yml?
db. See the image's documentation on docs.docker.com and the use of theadminerimage (docs.docker.com/samples/library/postgres/…). Second, the Dockerfile would benefit from reducing the number of layers created by reducing the number ofRUNcommands. For exampleRUN apt-get update && apt-get -y install python-pip(you don't need the finalapt-get update).