skip to Main Content

I’m using windows with WSL2 installed.
I built container with below script — NodeJS server

# Docker script for nestjs server -- For testing
FROM node:18

RUN mkdir -p /app
WORKDIR /app

COPY ./ ./

RUN npm ci

ENTRYPOINT ["npm", "run", "start:dev"]
EXPOSE 3000

And build image with docker build .
And run with `docker run -p 3000:3000 (NodeJS server is listening on port 3000)

And there are ‘ping’ http request inside server http://<host>:<port>/ping and should return ‘pong’ response.
I tried this request over different envs.

  1. Windows (WSL2 is running and container is running)
    Send request via Postman
GET http://localhost:3000

response is

Error: connect ECONNREFUSED 127.0.0.1:3000
  1. Inside WSL ubuntu
curl http://localhost:3000

gets same response

curl: (7) Failed to connect to localhost port 3000 after 0 ms: Connection refused
  1. Inside container
curl http://localhost:3000

reponse successfully retrieved

pong

Now I’m sure that server is running.

Container inspect list below,

{
    "Id": "c1191fd5b2deb5adcf89af8ccf5ea18812bee85bc9c3d90465e26a42ae2bfe88",
    "Created": "2023-10-12T09:50:48.266404824Z",
    "Path": "npm",
    "Args": [
        "run",
        "start:dev",
        "-p",
        "3000:3000",
        "--name",
        "test"
    ],
    "State": {
        "Status": "running",
        "Running": true,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 19939,
        "ExitCode": 0,
        "Error": "",
        "StartedAt": "2023-10-12T09:50:48.700406605Z",
        "FinishedAt": "0001-01-01T00:00:00Z"
    },
    "Image": "sha256:6912c4d03d52821984540a037ac30b1a3e7111bf9d560c0b99faafceb7559c58",
    "ResolvConfPath": "/var/lib/docker/containers/c1191fd5b2deb5adcf89af8ccf5ea18812bee85bc9c3d90465e26a42ae2bfe88/resolv.conf",
    "HostnamePath": "/var/lib/docker/containers/c1191fd5b2deb5adcf89af8ccf5ea18812bee85bc9c3d90465e26a42ae2bfe88/hostname",
    "HostsPath": "/var/lib/docker/containers/c1191fd5b2deb5adcf89af8ccf5ea18812bee85bc9c3d90465e26a42ae2bfe88/hosts",
    "LogPath": "/var/lib/docker/containers/c1191fd5b2deb5adcf89af8ccf5ea18812bee85bc9c3d90465e26a42ae2bfe88/c1191fd5b2deb5adcf89af8ccf5ea18812bee85bc9c3d90465e26a42ae2bfe88-json.log",
    "Name": "/admiring_albattani",
    "RestartCount": 0,
    "Driver": "overlay2",
    "Platform": "linux",
    "MountLabel": "",
    "ProcessLabel": "",
    "AppArmorProfile": "",
    "ExecIDs": null,
    "HostConfig": {
        "Binds": null,
        "ContainerIDFile": "",
        "LogConfig": {
            "Type": "json-file",
            "Config": {}
        },
        "NetworkMode": "default",
        "PortBindings": {},
        "RestartPolicy": {
            "Name": "no",
            "MaximumRetryCount": 0
        },
        "AutoRemove": false,
        "VolumeDriver": "",
        "VolumesFrom": null,
        "ConsoleSize": [
            30,
            120
        ],
        "CapAdd": null,
        "CapDrop": null,
        "CgroupnsMode": "host",
        "Dns": [],
        "DnsOptions": [],
        "DnsSearch": [],
        "ExtraHosts": null,
        "GroupAdd": null,
        "IpcMode": "private",
        "Cgroup": "",
        "Links": null,
        "OomScoreAdj": 0,
        "PidMode": "",
        "Privileged": false,
        "PublishAllPorts": false,
        "ReadonlyRootfs": false,
        "SecurityOpt": null,
        "UTSMode": "",
        "UsernsMode": "",
        "ShmSize": 67108864,
        "Runtime": "runc",
        "Isolation": "",
        "CpuShares": 0,
        "Memory": 0,
        "NanoCpus": 0,
        "CgroupParent": "",
        "BlkioWeight": 0,
        "BlkioWeightDevice": [],
        "BlkioDeviceReadBps": [],
        "BlkioDeviceWriteBps": [],
        "BlkioDeviceReadIOps": [],
        "BlkioDeviceWriteIOps": [],
        "CpuPeriod": 0,
        "CpuQuota": 0,
        "CpuRealtimePeriod": 0,
        "CpuRealtimeRuntime": 0,
        "CpusetCpus": "",
        "CpusetMems": "",
        "Devices": [],
        "DeviceCgroupRules": null,
        "DeviceRequests": null,
        "MemoryReservation": 0,
        "MemorySwap": 0,
        "MemorySwappiness": null,
        "OomKillDisable": false,
        "PidsLimit": null,
        "Ulimits": null,
        "CpuCount": 0,
        "CpuPercent": 0,
        "IOMaximumIOps": 0,
        "IOMaximumBandwidth": 0,
        "MaskedPaths": [
            "/proc/asound",
            "/proc/acpi",
            "/proc/kcore",
            "/proc/keys",
            "/proc/latency_stats",
            "/proc/timer_list",
            "/proc/timer_stats",
            "/proc/sched_debug",
            "/proc/scsi",
            "/sys/firmware"
        ],
        "ReadonlyPaths": [
            "/proc/bus",
            "/proc/fs",
            "/proc/irq",
            "/proc/sys",
            "/proc/sysrq-trigger"
        ]
    },
    "GraphDriver": {
        "Data": {
            "LowerDir": "/var/lib/docker/overlay2/128326c1aa78b17594943f202a4c220a788ef6ba70bf96c4cc819cc68a133514-init/diff:/var/lib/docker/overlay2/c6b5zzb2ik0cfkf0ewps2bgwt/diff:/var/lib/docker/overlay2/zr4cxqstgu02ra7glrh1qa08a/diff:/var/lib/docker/overlay2/s3imxggw3el9422u13dxe8v3a/diff:/var/lib/docker/overlay2/mh5zr4dyz1tvwxoz4b6p1binn/diff:/var/lib/docker/overlay2/0d234ff6425d4859ea83dee385320c4243bfdbfb91415fd89e663cd0bff0655a/diff:/var/lib/docker/overlay2/6275f330dee99c6d3b688cde48fe814e1d30936789894bf2584c7944765301bf/diff:/var/lib/docker/overlay2/26fa7a8e809345b31f98c2e8261d60a15ce58a841e5b7b56556a050446acc827/diff:/var/lib/docker/overlay2/79f57d81e2c97ab6aaf3d8f036a38356464cccc0fd62ac70f02bb15814dce841/diff:/var/lib/docker/overlay2/28af674bb584053258e45168acf22851dc94b85714b51439fa23db9aec3be736/diff:/var/lib/docker/overlay2/19bec54d77725cb724f285a52308b60955347376d383dcb86121292760edebd6/diff:/var/lib/docker/overlay2/451daadeb1dfc02492a68c327f3a4523d653fa67d3643a3f7ab46a123145f803/diff:/var/lib/docker/overlay2/c2e3da41d2357797896be0eadcb31e82fad1cb46113c7d9c09593a491c32d6e7/diff",
            "MergedDir": "/var/lib/docker/overlay2/128326c1aa78b17594943f202a4c220a788ef6ba70bf96c4cc819cc68a133514/merged",
            "UpperDir": "/var/lib/docker/overlay2/128326c1aa78b17594943f202a4c220a788ef6ba70bf96c4cc819cc68a133514/diff",
            "WorkDir": "/var/lib/docker/overlay2/128326c1aa78b17594943f202a4c220a788ef6ba70bf96c4cc819cc68a133514/work"
        },
        "Name": "overlay2"
    },
    "Mounts": [],
    "Config": {
        "Hostname": "c1191fd5b2de",
        "Domainname": "",
        "User": "",
        "AttachStdin": false,
        "AttachStdout": true,
        "AttachStderr": true,
        "ExposedPorts": {
            "3000/tcp": {}
        },
        "Tty": false,
        "OpenStdin": false,
        "StdinOnce": false,
        "Env": [
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
            "NODE_VERSION=18.18.1",
            "YARN_VERSION=1.22.19"
        ],
        "Cmd": [
            "-p",
            "3000:3000",
            "--name",
            "test"
        ],
        "Image": "6912c4d03d52821984540a037ac30b1a3e7111bf9d560c0b99faafceb7559c58",
        "Volumes": null,
        "WorkingDir": "/app",
        "Entrypoint": [
            "npm",
            "run",
            "start:dev"
        ],
        "OnBuild": null,
        "Labels": {}
    },
    "NetworkSettings": {
        "Bridge": "",
        "SandboxID": "db992a401db21abb9169c88b1a9b19aeb0baa3c396a6c1d997b56897e1c2adce",
        "HairpinMode": false,
        "LinkLocalIPv6Address": "",
        "LinkLocalIPv6PrefixLen": 0,
        "Ports": {
            "3000/tcp": null
        },
        "SandboxKey": "/var/run/docker/netns/db992a401db2",
        "SecondaryIPAddresses": null,
        "SecondaryIPv6Addresses": null,
        "EndpointID": "7a069d940d89b876d12d6c421ac5664819aa739ea906df22014566a742f6c848",
        "Gateway": "172.17.0.1",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "IPAddress": "172.17.0.2",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "MacAddress": "02:42:ac:11:00:02",
        "Networks": {
            "bridge": {
                "IPAMConfig": null,
                "Links": null,
                "Aliases": null,
                "NetworkID": "302bd2351bcf5c2f5e57291b101ed1ee4cf80cdc98ff746dc12a73f65267aedf",
                "EndpointID": "7a069d940d89b876d12d6c421ac5664819aa739ea906df22014566a742f6c848",
                "Gateway": "172.17.0.1",
                "IPAddress": "172.17.0.2",
                "IPPrefixLen": 16,
                "IPv6Gateway": "",
                "GlobalIPv6Address": "",
                "GlobalIPv6PrefixLen": 0,
                "MacAddress": "02:42:ac:11:00:02",
                "DriverOpts": null
            }
        }
    }
}

Seems port is exposed.
And also tried `docker port <my_container_name> and it result nothing (I don’t know why this does not show exposed port anyway)

docker ps result belows

CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS      NAMES
c1191fd5b2de   6912c4d03d52   "npm run start:dev -…"   12 minutes ago   Up 12 minutes   3000/tcp   admiring_albattani

Can you help me about why my server is not accessible from outside of container?
All seems normal I guess.

I’m assuming reason for connect rejection is port is not in use but dont know how to resolve it.

Thanks

— appended to post later —

I also configure server to listen on 0.0.0.0
NestJS code are blow

await app.listen(configService.get('server.port'), '0.0.0.0', () => {
        console.log(`=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=`);
        console.log(`=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Running NestJS Server =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=`);
        console.log(`=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=`);
        console.log(`   Environment: ${configService.get('server.env')}`);
        console.log(`Listening port: ${configService.get('server.port')}`);
        console.log(`=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=`);
    });
  • I tried both localhost url ‘localhost:3000’ and ‘127.0.0.1:3000’ on curl command and postman url.

2

Answers


  1. You need to listen on remote connections with 0.0.0.0. For example:

    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app.module';
    
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      await app.listen(3000, '0.0.0.0');
    }
    bootstrap();
    
    Login or Signup to reply.
  2. Try starting the container with 0.0.0.0.

    $ docker run -h 0.0.0.0 -p 3000:3000 …

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search