Search code examples
dockerubuntu-18.04pm2

How to run a docker container with pm2?


I have a system that has many components and one of them is a docker container. I'd like to manage all these components with Pm2.

I'm able to run the Node.js scripts with Pm2, but I have a problem starting the docker container on Ubuntu 18.04.2 LTS.

I have a script "start.sh" that already starts the docker container in the right way.

The script is:

docker run -d -it -p 21083:21083 -p 9001:9001 -v /home/myhome/mqtt_broker/conf/mosquitto.conf:/mosquitto/config/mosquitto.conf -v /home/myhome/mqtt_broker/authentication/auth.txt:/mosquitto/auth.txt -v /home/myhome/mqtt_broker/acl/aclfile.txt:/mosquitto/aclfile.txt eclipse-mosquitto

I'm trying to start this script with PM2 in this way:

pm2 start /home/myhome/mqtt_broker/startBroker.sh --name=BrokerMqtt

After launching this command I can see:

  • 'docker ps' says that the container is up,
  • BrokerMqtt in the processes list of pm2 with the status 'errored',
  • in the log of pm2 I can see many of these errors:

    docker:

    Error response from daemon: driver failed programming external connectivity on endpoint jolly_meninsky (fefe45df2d338d89a4f8232873779e41bcaa1b846a463bc035d59c5ae09b26e0): Bind for 0.0.0.0:21083 failed: port is already allocated.

Why the script start.sh, that works if launched alone, fails with Pm2?


Solution

  • You might want to try using pm2 with npm start. In your package.json file, add a start script

      "start": "/home/myhome/mqtt_broker/startBroker.sh && sleep 5 && node Node"
    

    Then you can start your application with

    pm2 start npm --name BrokerMqtt -- start
    

    You can adjust the time of sleep, I added that to make sure the container is ready to serve your node program.

    Improvements you can make:

    1. give a name to the container
    2. make sure that container is not running before you run your bash script, here's one way to check:
    docker inspect container_name|grep Running