How to run socket on docker container ip address

Viewed 30

Final goal - run socket that is binding on the container ip and ready to accept clients from outside the docker.

I was able to run a container and give it a static IP address using the following commands,

  • First, I created the network:
docker network create --subnet=10.1.0.5/16 mynetwork
  • After, I created my container using this command:
docker run --net mynetwork --ip 10.1.0.5 -p 3000:3000 -d --name relay image
  • The image I used running a command that is running the python code as you can see below:
FROM python:latest

WORKDIR /usr/src/app

COPY ./relay.py /usr/src/app/

CMD [ "python3", "relay.py" ] # running the python code (socket)
  • I verified the ip address of the container using this command: (I am getting the wanted output: '10.1.0.5')
docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' relay
  • And this is the python code that the container is running:
import socket


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


if __name__ == "__main__":
    main()

For some reason the socket is listening on '0.0.0.0:3000' and accepting clients only when connecting to the localhost:3000, when trying to connect though '10.1.0.5' ip address it won't work.

Can someone enlighten me and explain to me what I'm missing?.

0 Answers
Related