fussybeaver / bollard

Docker daemon API in Rust

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to publish ports?

banool opened this issue · comments

I have read a few issues in this repo asking a similar question and unfortunately many of them are closed by folks without saying how they actually fixed them, for example #322.

How would I express this:

-p 127.0.0.1:5433:5432

with bollard? This means expose 5432 from inside the container to the host on 127.0.0.1 as 5433.

I have tried this:

const POSTGRES_DEFAULT_PORT: u16 = 5432;

fn myfunc(other_port: u16) {
    let port = other_port.to_string();
    let exposed_ports = Some(hashmap! {port.as_str() => hashmap!{}});
    let host_config = Some(HostConfig {
        port_bindings: Some(hashmap! {
            POSTGRES_DEFAULT_PORT.to_string() => Some(vec![PortBinding {
                host_ip: Some("127.0.0.1".to_string()),
                host_port: Some(port),
            }]),
        }),
        ..Default::default()
    });

    let config = Config {
        image: Some(POSTGRES_IMAGE),
        exposed_ports,
        host_config,
        ..Default::default()
    };
}

But unfortunately it doesn't work, you can't connect on the host.

I think I'll figure this out myself soon, I'm just leaving this so it'll help someone else out later.

Alright here is how you do it:

const POSTGRES_DEFAULT_PORT: u16 = 5432;

fn myfunc(other_port: u16) {
    let port = other_port.to_string();
    let exposed_ports = Some(hashmap! {POSTGRES_DEFAULT_PORT => hashmap!{}});
    let host_config = Some(HostConfig {
        port_bindings: Some(hashmap! {
            POSTGRES_DEFAULT_PORT.to_string() => Some(vec![PortBinding {
                host_ip: Some("127.0.0.1".to_string()),
                host_port: Some(port),
            }]),
        }),
        ..Default::default()
    });

    let config = Config {
        image: Some(POSTGRES_IMAGE),
        exposed_ports,
        host_config,
        ..Default::default()
    };
}

In short, put the inner port in exposed ports and as the key in port bindings, use the outer port in the value of port bindings.

You don't actually need the exposed_ports field to publish a port, only the port_bindings map within host_config.

exposed_ports is equivalent to the docker run --expose flag or Dockerfile EXPOSE statement - it doesn't actually do anything and is basically just a hint for clients regarding which ports should be published.

Ah good to know, ty!