Docker & Nodejs – Part I – Creating A Docker Ready Nodejs App
What I like in Docker is its simplicity, once you master how to use it, developing and running applications becomes simpler. In this serie of tutorial I am using Docker Compose to create a container for a Nodejs application.
Let’s start by creating a sample app:
mkdir nodeapp && cd nodeapp mkdir app && cd app echo "console.log('Hello, World!')" > main.js cd ..
Let’s start by using Node image to run into the Docker container :
Create a file called
web: image: nodesource/node:4.0 volumes: - ./app:/usr/src/app ports: - 3000:3000
By the code above we would like to use nodesource/node:4.0 image from the official Docker repository and we mounted the application source files to
which is the Node app root directory.
Let’s try to create the machine:
You will certainly have errors similar to the next ones:
web_1 | npm ERR! Linux 3.16.0-38-generic web_1 | npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "start" web_1 | npm ERR! node v4.0.0 web_1 | npm ERR! npm v2.14.2 web_1 | npm ERR! path /usr/src/app/package.json web_1 | npm ERR! code ENOENT web_1 | npm ERR! errno -2 web_1 | npm ERR! syscall open web_1 | web_1 | npm ERR! enoent ENOENT: no such file or directory, open '/usr/src/app/package.json' web_1 | npm ERR! enoent This is most likely not a problem with npm itself web_1 | npm ERR! enoent and is related to npm not being able to find a file. web_1 | npm ERR! enoent web_1 | web_1 | npm ERR! Please include the following file with any support request: web_1 | npm ERR! /usr/src/app/npm-debug.log nodeapp_web_1 exited with code 254
To execute the Node app we should run:
and to keep the container running without exiting we should add an infinite loop and that’s why I added a script
cat start.sh node main.js while : do sleep 1d done
Let’s add the script as an entrypoint to the Docker container
web: image: nodesource/node:4.0 volumes: - ./app:/usr/src/app - ./start.sh:/start.sh ports: - 3000:3000 entrypoint: "/bin/sh -c /start.sh"
If you are having some problems, think about running
on the files that should be executed (main.js & start.sh).
docker-compose up Creating nodeapp_web_1 Attaching to nodeapp_web_1 web_1 | Hello, World!
I will be posting other related posts (Docker + NodeJS ..etc) so wait for the Part II.
Happy Hacking !