Home > Software engineering >  Dockerizing a MERN stack app, how to define ports
Dockerizing a MERN stack app, how to define ports

Time:09-15

I want to dockerize my MERN app, here is the dockerfile for my frontend:

FROM node:18.8-alpine
COPY . ./app
WORKDIR /app
RUN npm install
EXPOSE 3000
CMD ["npm", "start"]

and here is the dockerfile for my backend:

FROM node:18.8-alpine
COPY . ./app
WORKDIR /app
RUN npm install
EXPOSE 3000
CMD ["node", "server.js"]

I also want to use docker-compose to run both frontend and backend together and this is the config file:

version: '3.8'
services:
  backend:
    build: ./backend
    container_name: backend_C
    ports:
      - 80:80
  frontend:
    build: ./frontend
    container_name: frontend_C
    ports:
      - 3000:3000

    stdin_open: true
    tty: true

The problem is since both my backend and frontend run on port 3000, there would be a conflict when I run my images. I don't know how to specify and change the ports for them.

CodePudding user response:

You can simply specify different host ports mapping to the same container ports:

version: '3.8'
services:
  backend:
    build: ./backend
    container_name: backend_C
    ports:
      - 3000:3000
  frontend:
    build: ./frontend
    container_name: frontend_C
    ports:
      - 8080:3000

    stdin_open: true
    tty: true

Now your backend is available on port 3000 and your frontend on port 8080

  • Related