Docker exits with code 0 when using pm2 start
Asked Answered
E

2

7

My Dockerfile contains the pm2 start command as follows:

FROM node:10

WORKDIR /usr/src/app

COPY . .

# ...

EXPOSE 8080

CMD [ "pm2", "start", "npm", "--", "start" ]

However the container exits straightaway after pm2 logs successfully starting:

[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
[PM2] Starting /usr/local/bin/npm in fork_mode (1 instance)
[PM2] Done.

How can I get the container to stay running with pm2?

Essive answered 1/5, 2019 at 12:42 Comment(0)
E
27

The problem is that pm2 start runs pm2 as a daemon ("in the background"), which Docker isn't aware of.

You need to use pm2-runtime to make it run in the foreground:

CMD [ "pm2-runtime", "start", "npm", "--", "start" ]

See pm2 "Container integration" docs.

Essive answered 1/5, 2019 at 12:42 Comment(1)
pm2-runtime also exits with status code 0. I'm using CMD [ "pm2-runtime", "npm", "--", "dev" ] The project is graphql prisma with typescript. This is the package.json's npm dev: "dev": "ts-node-dev --no-notify --respawn --transpile-only src/server",Robson
H
1

Also faced this issue of immediately stopping container with pm2-runtime usage.

I decided to change last line to:

CMD ["pm2-runtime", "dist/index.js", "--no-daemon"]

That resolved my issue.

Thus, in your case it could be:

CMD ["pm2-runtime", "start", "--no-daemon", "npm", "--", "start"]
Halves answered 16/9, 2023 at 15:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.