简体   繁体   中英

How can I expose two ports of the same nodejs app on docker

I am running a node js app on port 3002 and implemented a socket on port 3003 on the same app.

So in localhost when I hit 3002 I can hit my app and when I hit 3003 I can connect with the socket.

I want to implement the same result using docker but I can not connect with the socket.

Here are my Dockerfile and docker-compose.yml file

Dockerfile

FROM node:16.15-alpine3.15 As development

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install --ignore-scripts --only=development

COPY . .

RUN npm run build

FROM node:16.15-alpine3.15 As production

ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install --ignore-scripts --only=production

COPY . .

COPY --from=development /usr/src/app/dist ./dist

EXPOSE 3000
EXPOSE 3003

CMD ["node", "dist/main"]

docker-compose.yml

version: '3.8'

networks:
  global_network:
    external: true

services:
  cos_backend:
    image: 'node:16.15-alpine3.15'
    container_name: cos_backend
    restart: unless-stopped
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      -  "3002:3000"
      -  "3003:3000"
    networks:
      - global_network

The second ports: number always matches the port number that the process inside the container is listening on.

In your example, you're remapping host port 3002 to container port 3000, but you're also remapping host port 3003 to the same port (the HTTP port). So you need to change the second port number

ports:
  - '3002:3000'  # host port 3002 -> container port 3000 (HTTP)
  - '3003:3003'  # host port 3003 -> container port 3003 (socket)
  #       ^^^^     second number is always the fixed container port

There's not usually a need for the two port numbers to match; the important thing is that the second port number matches what's running inside the container.

(Terminology-wise, "expose" refers to a specific setting from first-generation Docker networking. It's still standard practice to EXPOSE ports in your Dockerfile that your container will listen on but it doesn't actually do anything. I tend to talk about "publishing ports" for the Compose ports: setting.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM