點燈坊

失くすものさえない今が強くなるチャンスよ

Running Node by Docker on AWS EC2

Sam Xiao's Avatar 2021-11-08

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 development
  • build : build image by version

Start Node

$ yarn dev

Run yarn dev to start Node on local machine.

push000

Build Node Image

$ yarn build

Run yarn build to build image.

push001

$ docker images

List all image we made.

push002

Tag Image

$ docker tag node-lab:1.0.0 oomusou/node-lab

Use docker tag to create a tag refers to source image.

push003

Push Image

$ docker push oomusou/node-lab

Use docker push to push image to Docker Hub.

push004

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.

push005

EC2

push006

Transfer docker-compose.yml to EC2.

$ docker-compose up

Use docker-compose up to start container on EC2.

push007

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