According to the Docker Compose Docs: Networking:
By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.
For example, suppose your app is in a directory called
myapp, and yourdocker-compose.ymllooks like this:version: "3" services: web: build: . ports: - "8000:8000" depends_on: - db db: image: postgres environment: POSTGRES_PASSWORD: testpass ports: - "8001:5432"When you run docker-compose up, the following happens:
- A network called
myapp_defaultis created.- A container is created using
web’s configuration. It joins the networkmyapp_defaultunder the nameweb.- A container is created using
db’s configuration. It joins the networkmyapp_defaultunder the namedb.
I put that exact docker-compose.yml in a directory with this Dockerfile:
FROM alpine
RUN ping -c 1 db
When I run docker-compose up, I get a connection error to the db container.
$ docker-compose up
Building web
Step 1/2 : FROM alpine
latest: Pulling from library/alpine
df20fa9351a1: Pull complete
Digest: sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321
Status: Downloaded newer image for alpine:latest
---> a24bb4013296
Step 2/2 : RUN ping -c 1 db
---> Running in cf64bfcb72eb
ping: bad address 'db'
ERROR: Service 'web' failed to build : The command '/bin/sh -c ping -c 1 db' returned a non-zero code: 1
If I put a node app in the Dockerfile, I can't make database connections to the db URI at postgres://postgres:postgres@db/postgres either.
I've tried using links and depends_on as well as the healthcheck for postgres advised in other SE answers. (EDIT: Added depends_on to compose file). Nothing has worked. Why can't I connect to the db container?
depends_onhas no effect. – ki9 Sep 18 '20 at 20:31docker-composeversion: "3"thatdepends_on:has been deprecated. – K8sN0v1c3 Sep 23 '20 at 03:18CMDdirective solved it. For the record, the latest postgres image also requires thePOSTGRES_PASSWORDenv var. I will add that into the question. – ki9 Sep 24 '20 at 01:42