how can i run two different nodejs apps in one docker image?
two different CMD [ "node", "app.js"]
and CMD [ "node", "otherapp.js"]
won't work, cause there can be only one CMD
directive in Dockerfile.
It's ok to have multiple processes, but to get the most benefit out of Docker, avoid one container being responsible for multiple aspects of your overall application. You can connect multiple containers using user-defined networks and shared volumes.
When a Docker user runs an image, it becomes one or multiple container instances. The container's initial state can be whatever the developer wants — it might have an installed and configured web server, or nothing but a bash shell running as root.
With multi-stage builds, you use multiple FROM statements in your Dockerfile. Each FROM instruction can use a different base, and each of them begins a new stage of the build. You can selectively copy artifacts from one stage to another, leaving behind everything you don't want in the final image.
Docker's main purpose is not parallelisation but isolation and portability but you can use it to run processes in parallel as you can do it without Docker.
I recommend using pm2
as the entrypoint process which will handle all your NodeJS applications within docker image. The advantage of this is that pm2
can bahave as a proper process manager which is essential in docker. Other helpful features are load balancing, restarting applications which consume too much memory or just die for whatever reason, and log management.
Here's a Dockerfile
I've been using for some time now:
#A lightweight node image
FROM mhart/alpine-node:6.5.0
#PM2 will be used as PID 1 process
RUN npm install -g [email protected]
# Copy package json files for services
COPY app1/package.json /var/www/app1/package.json
COPY app2/package.json /var/www/app2/package.json
# Set up working dir
WORKDIR /var/www
# Install packages
RUN npm config set loglevel warn \
# To mitigate issues with npm saturating the network interface we limit the number of concurrent connections
&& npm config set maxsockets 5 \
&& npm config set only production \
&& npm config set progress false \
&& cd ./app1 \
&& npm i \
&& cd ../app2 \
&& npm i
# Copy source files
COPY . ./
# Expose ports
EXPOSE 3000
EXPOSE 3001
# Start PM2 as PID 1 process
ENTRYPOINT ["pm2", "--no-daemon", "start"]
# Actual script to start can be overridden from `docker run`
CMD ["process.json"]
process.json
file in the CMD
is described here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With