Launch two nodejs app inside Docker container using pm2

4.8k Views Asked by At

I'm trying to launch 2 nodejs app inside a Docker container using PM2, so I made a custom Dockerfile with all the projects config

FROM node:argon

RUN npm install pm2 -g --silent

VOLUME ./src/app:/usr/src/app
WORKDIR /usr/src/app

RUN git clone https://github.com/yoonic/atlas.git backend
RUN cd backend && \
    npm i --silent && \
    pm2 start npm --name "backend" -- run dev --no-daemon

RUN git clone https://github.com/yoonic/nicistore.git frontend
RUN cd frontend && \
    npm i --silent && \
    sed -i "s#api.atlas.baseUrl#http://localhost:8000/v1#" config/client/development.js && \
    pm2 start npm --name "frontend" -- run dev --no-daemon

I start this container with docker-compose up with this config

# NodeJS
nodejs:
  build: docker/nodejs
  container_name: nodejs
  ports:
    - 53000:3000
    - 54000:4000

When all the container is set up, I get the PM2 process list in my terminal then docker-compose start all my containers but I the nodejs one fail instantly

nodejs exited with code 0

My nodejs app are working inside my container but this one exit instantly...

This the right way to make this work ? PM2 is maybe not needed ?

How can I make this working ?

EDIT

The container exit when I'm not using --no-daemon because it think everything is done. But when I'm using --no-daemon the build process is never finished because it show me nodejs app logs

2

There are 2 best solutions below

0
On BEST ANSWER

Use a process file to manage these two applications: http://pm2.keymetrics.io/docs/usage/application-declaration/

For example - process.yml:

apps:
  - script : 'npm'
    args   : 'run dev'
    cwd    : './backend'
    name   : 'backend'
  - script : 'npm'
    args   : 'run dev'
    cwd    : './frontend'
    name   : 'frontend'

Then in the Dockerfile:

CMD ['pm2-docker', 'process.yml']

Documentation about PM2/Docker integration: http://pm2.keymetrics.io/docs/usage/docker-pm2-nodejs/

1
On

First of all, though you can run several processes in one container usually the best way to go is to use just one process per container. So you would have two services in your docker-compose.yml - one for backend and another for frontend.

There are some problems in your Dockerfile that need fixing:

  1. Use ADD or COPY instead of VOLUME to copy files to container
  2. Use RUN command just for installing npm packages etc. to prepare an image.
  3. Use COMMAND or ENTRYPOINT to define the command that is run when the container is started.

So, the reason why your container is exiting is that you don't specify your own COMMAND and thus the default command from node:argon is run. As the default command is to start Node REPL and it exits if the container is not run in interactive mode, your container exits immediately on start-up.

I'm a bit busy now and can't prepare a full example with working code. Can you find your path forward with these tips? :)