Docker-compose containers can't connect to each other
The Dockerfile specifies how a container image is built.  The Dockerfile’s RUN command is trying to ping the db container, which is not yet running during the build phase.
Once the container images have been created, compose will start the containers and they will be able to address each other via their service names (db and web).
To accomplish what you want, an adjustment to your Dockerfile will need to be made.  Replace RUN with CMD.  This will allow the container to execute your ping command when it launches.
FROM alpine
CMD ping -c 1 db

Now your docker-compose up will build the web image, launch the db container and then launch your web container which will successfully execute a ping:
&gt; docker-compose up
Creating network &quot;simple_default&quot; with the default driver
Building web
Step 1/2 : FROM alpine
 ---&gt; a24bb4013296
Step 2/2 : CMD ping -c 1 db
 ---&gt; Running in 0c210f0936fd
Removing intermediate container 0c210f0936fd
 ---&gt; 7c0ed50ad4e8
Successfully built 7c0ed50ad4e8
Successfully tagged simple_web:latest
WARNING: Image for service web was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Creating simple_db_1 ... done
Creating simple_web_1 ... done
Attaching to simple_db_1, simple_web_1

... output omitted

web_1  | PING db (172.19.0.2): 56 data bytes
web_1  | 64 bytes from 172.19.0.2: seq=0 ttl=64 time=0.218 ms
web_1  |
web_1  | --- db ping statistics ---
web_1  | 1 packets transmitted, 1 packets received, 0% packet loss
web_1  | round-trip min/avg/max = 0.218/0.218/0.218 ms
db_1   |
db_1   | Data page checksums are disabled.
db_1   |
db_1   | fixing permissions on existing directory /var/lib/postgresql/data ... ok
db_1   | creating subdirectories ... ok
db_1   | selecting dynamic shared memory implementation ... posix
db_1   | selecting default max_connections ... 100
db_1   | selecting default shared_buffers ... 128MB
db_1   | selecting default time zone ... Etc/UTC
db_1   | creating configuration files ... ok
db_1   | running bootstrap script ... ok
db_1   | performing post-bootstrap initialization ... ok
simple_web_1 exited with code 0