Dockerizzare un'applicazione nodejs: pm2 dovrebbe funzionare quando avvio per la prima volta il container

Aug 18 2020

Ho la seguente applicazione express / node:

FROM node:12
WORKDIR /usr/share/jtapp
COPY  package*.json ./
RUN apt-get update
RUN apt-get install -y net-tools
RUN npm install
RUN npm install pm2@latest -g
#RUN npm ci --only=production
COPY . .
EXPOSE 3000
RUN pm2 start server.js

Sembra costruire bene. Ma quando avvio l'immagine e mi collego tramite bash, non ci sono processi pm2 in esecuzione.

Ecco i risultati della compilazione:

Sending build context to Docker daemon  319.5kB                                                                                                                                                                                              Step 1/10 : FROM node:12                                                                                                                                                                                                                      ---> cfcf3e70099d                                                                                                                                                                                                                           Step 2/10 : WORKDIR /usr/share/jtapp                                                                                                                                                                                                     ---> Using cache                                                                                                                                                                                                                             ---> 2c2e2e1e92f2                                                                                                                                                                                                                           Step 3/10 : COPY  package*.json ./                                                                                                                                                                                                            ---> Using cache                                                                                                                                                                                                                             ---> 57829fd5e9d7                                                                                                                                                                                                                           Step 4/10 : RUN apt-get update                                                                                                                                                                                                                ---> Using cache                                                                                                                                                                                                                             ---> c0bbfed43ca8                                                                                                                                                                                                                           Step 5/10 : RUN apt-get install -y net-tools                                                                                                                                                                                                  ---> Using cache                                                                                                                                                                                                                             ---> 0b34759d8298                                                                                                                                                                                                                           Step 6/10 : RUN npm install                                                                                                                                                                                                                   ---> Using cache                                                                                                                                                                                                                             ---> 6abc42a9f8a3                                                                                                                                                                                                                           Step 7/10 : RUN npm install pm2@latest -g                                                                                                                                                                                                     ---> Running in 2fafacd302bf                                                                                                                                                                                                                /usr/local/bin/pm2 -> /usr/local/lib/node_modules/pm2/bin/pm2                                                                                                                                                                                /usr/local/bin/pm2-dev -> /usr/local/lib/node_modules/pm2/bin/pm2-dev                                                                                                                                                                        /usr/local/bin/pm2-docker -> /usr/local/lib/node_modules/pm2/bin/pm2-docker                                                                                                                                                                  /usr/local/bin/pm2-runtime -> /usr/local/lib/node_modules/pm2/bin/pm2-runtime               
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@~2.1.2 (node_modules/pm2/node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

+ [email protected]
added 185 packages from 191 contributors in 10.165s
Removing intermediate container 2fafacd302bf
 ---> 11d15b993ca2
Step 8/10 : COPY . .
 ---> efab8283bbd9
Step 9/10 : EXPOSE 3000
 ---> Running in aae343a75727
Removing intermediate container aae343a75727
 ---> b97825863317
Step 10/10 : RUN pm2 start server.js
 ---> Running in f0d14c61a3a6
[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
[PM2] Starting /usr/share/jtapp/server.js in fork_mode (1 instance)
[PM2] Done.
┌─────┬───────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id  │ name      │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
├─────┼───────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0   │ server    │ default     │ 1.0.0   │ fork    │ 28       │ 0s     │ 0    │ online    │ 0%       │ 28.2mb   │ root     │ disabled │
└─────┴───────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘
Removing intermediate container f0d14c61a3a6
 ---> 859f8479f3a6
Successfully built 859f8479f3a6

Quindi è così che avvio il contenitore e lo collego:

lab:/var/lib/git/jtapp# docker run -d -it --name jtapp -p 3000:3000 jtapp bash
d62927716ab593376c4e38f7d4d05007223ce2adfcb4997e722b81ad7260f114
lab:/var/lib/git/jtapp # docker exec -it jtapp  bash
root@d62927716ab5:/usr/share/jtapp # pm2
usage: pm2 [options] <command>

pm2 -h, --help             all available commands and options
pm2 examples               display pm2 usage examples
pm2 <command> -h           help on a specific command

Access pm2 files in ~/.pm2
root@d62927716ab5:/usr/share/jtapp #

Ma sono in grado di avviare tutto manualmente una volta che sono all'interno del contenitore, in questo modo:

root@d62927716ab5:/usr/share/jtapp# pm2 start server.js
[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
[PM2] Starting /usr/share/jtapp/server.js in fork_mode (1 instance)
[PM2] Done.
┌─────┬───────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id  │ name      │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
├─────┼───────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0   │ server    │ default     │ 1.0.0   │ fork    │ 37       │ 0s     │ 0    │ online    │ 0%       │ 28.4mb   │ root     │ disabled │
└─────┴───────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘

MODIFICA 1

Cambiato:

 RUN pm2 start server.js 

per

 CMD ["pm2", "start", "server.js"]

E poi ho provato a ricostruire / avviare un contenitore. quando eseguo un "pm2 ls" torna ancora vuoto.

root@a8b7eb21d307:/usr/share/jtapp# pm2 ls
[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
┌────┬────────────────────┬──────────┬──────┬───────────┬──────────┬──────────┐
│ id │ name               │ mode     │ ↺    │ status    │ cpu      │ memory   │
└────┴────────────────────┴──────────┴──────┴───────────┴──────────┴──────────┘

MODIFICA 2

Quando rimuovo l'opzione "-d" nel mio comando di esecuzione:

lab:/var/lib/git/jtappd# docker run  -it --name jtapp -p 3000:3000 jtapp  bash
root@3cf4855372ec:/usr/share/jtapp# pm2 ls
[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
┌─────┬───────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id  │ name      │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
└─────┴───────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘
root@3cf4855372ec:/usr/share/jtapp#

MODIFICA 3

Quindi il Dockerfile ha questo aspetto ora:

FROM node:12
WORKDIR /usr/share/jtapp
COPY  package*.json ./
RUN apt-get update
RUN apt-get install -y net-tools
RUN npm install
RUN npm install pm2@latest -g
COPY . .
EXPOSE 3000
CMD ["npm", "run", "start:pm2"]

ecosistema.config.js ha il seguente aspetto:

lab:/var/lib/git/jtapp# cat ecosystem.config.js
module.exports = {
  apps: [{
    name: 'jtapp',
    script: './server.js', //entrypoint
    instances: 1,
    autorestart: true, // pm2 to restart if this app fails/stops
    max_memory_restart: '1G'
  }]
}

e la sezione script di package.json:

 1 {
 2   "name": "nodeserver",
 3   "version": "1.0.0",
 4   "description": "simple node server",
 5   "main": "index.js",
 6   "scripts": {
 7     "test": "echo \"Error: no test specified\" && exit 1",
 8     "start": "nodemon server.js",
 9     "start:pm2": "pm2 start ecosystem.config.js --no-daemon"
10   },

Il Dockerfile viene compilato senza errori. Ma quando avvio il contenitore ... server.js non è in esecuzione. pm2 è installato.

Ma non ci sono problemi ad avviarlo manualmente utilizzando il file dell'ecosistema una volta effettuato l'accesso al contenitore come puoi vedere di seguito:

root@d51117d757a3:/usr/share/jtapp# pm2 start ecosystem.config.js
[PM2][WARN] Applications jtapp not running, starting...
[PM2] App [jtapp ] launched (1 instances)
┌─────┬──────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id  │ name     │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
├─────┼──────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0   │ jtapp    │ default     │ 1.0.0   │ cluster │ 36       │ 0s     │ 0    │ online    │ 0%       │ 32.6mb   │ root     │ disabled │
└─────┴──────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘

Risposte

1 MohamadrezaRahimianGolkhandani Aug 19 2020 at 09:17

L'approccio migliore sarebbe usare ecosystem.config.js. Metti questo file nella directory principale del tuo progetto:


module.exports = {
  apps: [{
    name: 'app',
    script: 'src/index.js', // Your entry point
    instances: 1,
    autorestart: true, // THIS is the important part, this will tell PM2 to restart your app if it falls over
    max_memory_restart: '1G'
  }]
}

quindi installa pm2 come modulo npm nel tuo progetto e aggiungi questo script al tuo file package.json

...
scripts: {
...
  "start:pm2":"pm2 start ecosystem.config.js --no-daemon"
}

e infine usa questo CMD nel tuo dockerfile

CMD [ "npm", "run", "start:pm2" ]

MODIFICA 1

puoi trovare un progetto di esempio qui con dockerfile originale:

https://github.com/golkhandani/pm2_docker/tree/master

MODIFICA 2

Ho appena testato il repository con un altro ManjaroLinux e qui ci sono i comandi

git clone https://github.com/golkhandani/pm2_docker.git

docker build pm2_docker/ --tag pm2docker:test

docker run -p 3000:3000 -t pm2docker:test

l' -p 3000:3000arg dovrebbe essere aggiunto per accedere localmente al tuo server.

questi sono screenshot aggiuntivi che mostrano comando e risultati: