點燈坊

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

Running Express on AWS EC2 with Ubuntu

Sam Xiao's Avatar 2021-11-18

If we can run Express by Docker on the local machine, we can run Express by Docker on AWS EC2.

Version

Express 4.17.1
Ubuntu 20.04
Docker 20.10.7
Docker-compose 1.25.0

Express

app.js

import express from 'express'
import cors from 'cors'

let app = express ()
app.use (cors ())

app.get ('/api', (req, res) => res.send ('Hello World'))
app.listen (30, _ => console.log ('Express listen on port: 30'))

Express uses GET to send back Hello World.

Dockerfile

dockerfile

FROM node:alpine
WORKDIR /usr/src/app
COPY package.json ./package.json
RUN yarn install
COPY app.js .
CMD [ "node", "app.js" ]
  • Build Express image by Node image
  • Copy app.js to image

Docker Compose

docker-compose.yml

version: "3"
services:
  express:
    image: express:0.0.0    
    ports:
      - "3030:30"
    restart: always  
  • Run container by our image
  • Map port 3030 to internal port 30

NPM Config

package.json

{
  "type": "module",
  "name": "express-lab",
  "version": "0.0.0",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
  },
  "devDependencies": {
    "nodemon": "^2.0.13"
  },
  "scripts": {
    "dev": "nodemon app.js",
    "build": "docker build -t express:$npm_package_version ."
  }
}

Line 14

"build": "docker build -t express:$npm_package_version ."

Build image by dockerfile in the current directory.

Build Image

$ yarn build

Build image by calling NPM script.

express000

Run Container

$ docker-compose up -d

Run container by docker-compose.yml.

express001

Express on Local Machine

express002

Run Express successfully on localhost at port 8080.

Push Image

$ docker tag express:0.0.0 oomusou/express

Set tag from vue:0.0.0 to oomusou/express.

$ docker push oomusou/express

Push oomusou/express to Docker Hub.

express003

Login to EC2

$ ssh -i MyEC2.pem ubuntu@13.231.226.91

Login to Ubuntu server on AWS EC2 by user ubuntu.

express004

Docker Compose

docker-compose.yml

version: "3"
services:
  express:
    image: oomusou/express
    restart: always
    ports:
      - "3030:30"
  • Create docker-compose.yml on AWS EC2
  • Run container as oomusou/express image

Run Container

$ docker-compose up -d

Run container on AWS EC2.

express005

Inbound Rules

express006

AWS EC2 only opens port 22 for SSH connection by default, we have to add port 3030 for Express.

Express on EC2

express007

Run Express successfully on 13.231.226.91 at port 30300.

Conclusion

  • The most important step to run Vue on AWS EC2 is to open port 8080 on an inbound rule