As long as we install Docker and Docker Compose on AWS EC2, we can run Node by Docker on AWS EC2.
Version
Node 16.13.0
Node
index.js
console.log ('Hello World')
Only one line Hello World
to print on screen.
Dockerfile
dockerfile
FROM node:lts-alpine
ENV NODE_ENV=production
WORKDIR /usr/src/app
COPY package.json ./package.json
RUN yarn install
COPY index.js .
CMD [ "node", "index.js" ]
Build image by dockerfile
.
NPM Config
package.json
{
"type": "module",
"name": "node-lab",
"version": "1.0.0",
"main": "index.js",
"devDependencies": {
"nodemon": "^2.0.14"
},
"scripts": {
"dev": "nodemon index.js",
"build": "docker build -t node-lab:$npm_package_version ."
}
}
dev
: run Node on developmentbuild
: build image byversion
Start Node
$ yarn dev
Run yarn dev
to start Node on local machine.
Build Node Image
$ yarn build
Run yarn build
to build image.
$ docker images
List all image we made.
Tag Image
$ docker tag node-lab:1.0.0 oomusou/node-lab
Use docker tag
to create a tag refers to source image.
Push Image
$ docker push oomusou/node-lab
Use docker push
to push image to Docker Hub.
Docker Compose
docker-compose.yml
version: "3"
services:
node:
image: oomusou/node-lab
container_name: Node
Use docker-compose.yml
to describe container.
Start Container
$ docker compose up
Use docker compose up
to start container.
EC2
Transfer docker-compose.yml
to EC2.
$ docker-compose up
Use docker-compose up
to start container on EC2.
Node runs successfully by Docker on EC2.
Conclusion
- We don’t have to install Node runtime on AWS EC2, just build Node as image, install Docker and Docker Compose on EC2, then we can run Node on AWS EC2 successfully