简体   繁体   中英

docker-compose simple networking demo

I am new to docker and docker-compose and I'm trying to understand networking in docker. I have the following docker-compose.yml file

version: '3'

services:
  app0:
    build:
      context: ./
      dockerfile: Dockerfile0
  app1:
    build:
      context: ./
      dockerfile: Dockerfile1

And the Dockerfiles look like

FROM: python:latest

I'm using a python image because that's what I want for my actual use-case.

I run

docker-compose build
docker-compose up

output:

Building app0
Step 1/1 : FROM python:latest
 ---> 3624d01978a1
Successfully built 3624d01978a1
Successfully tagged docker_test_app0:latest
Building app1
Step 1/1 : FROM python:latest
 ---> 3624d01978a1
Successfully built 3624d01978a1
Successfully tagged docker_test_app1:latest

Starting docker_test_app0_1 ... done
Starting docker_test_app1_1 ... done
Attaching to docker_test_app0_1, docker_test_app1_1
docker_test_app0_1 exited with code 0
docker_test_app1_1 exited with code 0

From what I've read, docker-compose will create a default network and both containers will be attached to that network and should be able to communicate. I want to come up with a very simple demonstration of this, for example using ping like this:

docker-compose run app0 ping app1

output:

ping: app1: Name or service not known

Am I misunderstanding how docker-compose networking works? Should I be able to ping app1 from app0 and vice versa?

running on amazon linux. docker-compose version version 1.23.2, build 1110ad01

You need to add something (a script, via CMD ) to those Python containers that keeps them running, something listening on a port or a simple loop.

Right now they immediately terminate after starting and there is nothing to ping. (The whole container shuts down when its command finished)

Defining services in the docker-composer.yaml file maybe not not enough as if one service will be down the other one won't have information about it's IP address.

You can however create a dependence between them which will for example allow the instance to automatically start app1 service when you start app0.

Set following configuration:

version: '3'

services:
  app0:
    build:
      context: ./
      dockerfile: Dockerfile0
    depends_on:
      - "app1"
  app1:
    build:
      context: ./
      dockerfile: Dockerfile1

This is a good practice in case you want services to communicate between each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM