Docker files to docker compose

Viewed 145

Im new at docker. I am making a java sockets music server and i have 2 files. Client.java and Server.java. Both are in separate containers. To mention, i run both services in command line

Docker files

FROM java:8
COPY Server.java /
RUN javac Server.java
EXPOSE 25000
ENTRYPOINT ["java"]
CMD ["Server"]
FROM java:8
COPY Client.java /
RUN javac Client.java
EXPOSE 25000
ENTRYPOINT ["java"]
CMD ["Client"]

i create also a network for these two to communicate.

docker network create client_server_network

and i run the images as follows:

docker run --env SERVER_HOST_ENV=server --network-alias server --network client_server_network -it server

docker run --network client_server_network -it clientimage

Now i want to create a docker compose file with those two Dockerfiles and the network. This is what i have done so far:

version:'3'
services:
  client:
    image: java:8
    ports:
      -25000:25000
    network:
      default:
        name: client_server_network  
    

  server:
    image: java:8
    ports:
      -25000:25000
    environment:
      -SERVER_HOST_ENV=server 
    network:

My question is how to add the common network in both services. Also is the way i write my docker compose file correct?

2 Answers

Below is the code, by default both container is added to network named net and it must provide in the last line also

version:'3'
services:
  client:
    image: java:8
    ports:
      - 25000:25000
    networks:
      - client_server_network  
    

  server:
    image: java:8
    ports:
      - 25000:25000
    environment:
      - "SERVER_HOST_ENV=server" 
    networks:
      - client_server_network
networks:
  client_server_network:

Note that the network should be specified commonly at last in the same level of services and version. As indenting is a main factor in docker-compose. if it is incorrectly indent may shows error.

Delete all of the networks: blocks in the entire file. client and server will be usable as host names by these two containers.

This behavior is described further in Networking in Compose in the Docker documentation. If you don't declare top-level networks:, Compose creates a network called default, and if you don't declare networks: on a given service, Compose attaches it to that default network.

A functional translation of your two docker run commands would look like:

version: '3.8'
# Compose creates `networks: { default: }` on its own; you do not need
# top-level `networks:`
services:
  server: # <-- this name is usable as a host name
    image: server
    environment:
      - SERVER_HOST_ENV=server
    # Automatically on `networks: [default]`
  client:
    image: clientimage
Related