0

I am new in Rust and to study new language I have decided to write simple "server app" based on TcpListener. It's simple main function that looks like this:

fn main() {
    println!("Start server");
    let server = TcpListener::bind("127.0.0.1:7878").unwrap();
    match server.accept() {
        Ok((_socket, addr)) => {
            println!("new client: {:?}", addr);
            loop {
              //do something
            }
        }
        Err(e) => { println!("couldn't accept the client: {:?}", e) }
    }
    println!("server disconnect")
}

and also I have some client code that connect to listener

fn client() {
    match TcpStream::connect("127.0.0.1:7878") {
        Ok(mut stream) => {
            println!("connect to server");
            loop {
              // do some work
            }
        }
        Err(e) => { println!("couldn't connect to server: {:?}", e) }
    }
    println!("client disconnect")
}

When I run it from cmd everything works well but when I run it in docker conteiner I can not connect to listener

couldn't connect: Os { code: 10061, kind: ConnectionRefused, message: "No connection could be made because the target machine actively refused it." }

How can I fix it? I am new in Docker as in Rust so if you need more information pls leave a comment.

Dockerfile:

FROM rust:1.50

WORKDIR /usr/src/appname
COPY . .

RUN cargo install --path .
RUN cargo build --release
CMD cargo run

to run docker container I use docker run --rm -dp 7878:7878 appname

after that when I run client code it returns ok but server does not react (I expect that "new client" message will appear)

d.popovych
  • 359
  • 1
  • 3
  • 9
  • 2
    And where’s your Dockerfile / Docker compose – Mike Doe Mar 20 '21 at 19:53
  • 3
    Programs running in Docker containers need to bind to 0.0.0.0, not 127.0.0.1, or else they'll be unreachable from outside the container; [Deploying a minimal flask app in docker - server connection issues](https://stackoverflow.com/questions/30323224/deploying-a-minimal-flask-app-in-docker-server-connection-issues) is a similar situation, but for Python. – David Maze Mar 20 '21 at 20:11
  • @DavidMaze and should use 0.0.0.0 in client too? – d.popovych Mar 20 '21 at 20:16
  • @DavidMaze You saved my day! thank you. Could you pls explain why docker has 0.0.0.0 ip instead of 127.0.0.1 ? – d.popovych Mar 20 '21 at 20:30
  • 1
    0.0.0.0 means "everywhere"; you'd never make an outbound connection to it. Since the container has its own isolated network space, if it listens to 127.0.0.1 it's only the container-private localhost interface, but if it's 0.0.0.0 it will also accept connections from outside (try `docker run --rm busybox ifconfig` and you will see an artificial network interface). – David Maze Mar 20 '21 at 21:50

0 Answers0