Search code examples
docker-composecontainersdocker-network

How to isolate docker container from the host network (docker-compose)


I have a container that running a simple socket python script that listen on his ip address. I made a network for that container with the bridge as the driver. But when I am running the container I can access it from outside of his network using the localhost:port address. I want to isolate the container from anyone that is outside of his network. Can someone help me with that?.

This is my docker-compose file:*

version: '3.5'

services:
  relayG1_1:
    container_name: relayG1_1
    image: image
    command: python3 server.py 10.1.0.5
    ports:
      - 4000:4000/tcp
    networks:
      first_network:
        ipv4_address: 10.1.0.5

networks:
  first_network:
    name: first_network
    driver: bridge
    ipam:
     config:
       - subnet: 10.1.0.0/24
         gateway: 10.1.0.1

Solution

  • When you want to expose port on network, without being accessible from localhost you should use property expose instead of ports.

    An example :

    
    version: '3.5'
    
    services:
      relayG1_1:
        container_name: relayG1_1
        image: image
        command: python3 server.py 10.1.0.5
        expose:
          - "4000"
        networks:
          first_network:
            ipv4_address: 10.1.0.5
    
    networks:
      first_network:
        name: first_network
        driver: bridge
        ipam:
         config:
           - subnet: 10.1.0.0/24
             gateway: 10.1.0.1