How to use docker-compose network to connect with python socket

Viewed 47

I have a container that runs server python script using sockets and I also have a client python script that is trying to connect to that server (not on the container). My problem is that when I am connecting to the server via his ip it's not working, but if I am using localhost it is working just fine.
Can someone help me find what am I missing in the configuration of the container so it will simulate a real computer on the internet (that what I am trying to achieve).
my docker-compose

version: '3'

services:
  node1:
    container_name: node1
    build: ./
    command: python3 relay.py
    ports:
      - 4000:4000/tcp
    networks:
      app_net:
        ipv4_address: 10.10.10.4 # supposed to be the server IP

networks:
  app_net:
    driver: bridge
    ipam:
     config:
       - subnet: 10.10.10.0/16
         gateway: 10.10.10.1

the code that 'node1' container is running

import socket


def main():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.bind(('0.0.0.0', 4000))
        sock.listen(1)
        csock, addr = sock.accept()
        csock.sendall(b'hey')


if __name__ == "__main__":
    main()

the client code

import socket

host = "10.10.10.4"
port = 4000


def main():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.connect((host, port))
        data = sock.recv(1024).decode()
        print(data)


if __name__ == "__main__":
    main()

my final goal is to build a simulation of randoms computers that are not on my network just like real services online that I can communicate with.
Appreciate your time

0 Answers
Related