Dockerize a Typescript App in 15 mins
Introduction
We will download a simple TypeScript Hacker New sample app and dockerize it. We will also cover how to:
- Write
Dockerfile
anddocker-compose.yaml
- Run the NodeJs app using docker-compose
- Build a docker image
- Run the NodeJs app using
docker run
Part One: Start a simple NodeJs app
Clone the source code
git clone https://github.com/alickmail/hackernews-async-ts-docker
The original source code come from EggJs official repo:
Install packages, build typescript, start server
// Install all packages
npm install
// Compile all typescript to javascript
npm tsc
// Start the server
npm start
Visit the server
You should able to see this in the console:
hackernewsapp_1 | 2019-07-14 08:45:13,783 INFO 47 [egg-watcher:application] watcher start success
hackernewsapp_1 | 2019-07-14 08:45:13,783 INFO 47 [egg:core:ready_stat] end ready task /usr/src/app/node_modules/egg-watcher/lib/init.js:15:14, remain []
hackernewsapp_1 | 2019-07-14 08:45:13,804 INFO 29 [master] app_worker#1:47 started at 7001, remain 0 (1567ms)
hackernewsapp_1 | 2019-07-14 08:45:13,806 INFO 29 [master] egg started on <http://127.0.0.1:7001> (2464ms)
You can visit the url in browser http://127.0.0.1:7001
The service started successfully!
Part Two: Dockerize the app
Add this two file in the root of the project
// Dockerfile
FROM node:10.13.0-alpine# Env
ENV TIME_ZONE=Asia/Hong_Kong
ENV ENV_NAME dev
ENV EGG_SERVER_ENV dev
ENV NODE_ENV dev
ENV NODE_CONFIG_ENV dev# Set the timezone in docker
RUN apk --update add tzdata \\
&& cp /usr/share/zoneinfo/Asia/Hong_Kong /etc/localtime \\
&& echo "Asia/Hong_Kong" > /etc/timezone \\
&& apk del tzdata# Create Directory for the Container
WORKDIR /usr/src/app# Only copy the package.json file to work directory
COPY package.json .
# Install all Packages
RUN npm install# Copy all other source code to work directory
ADD . /usr/src/app
# TypeScript
RUN npm run tsc# Start
CMD [ "npm", "start" ]
EXPOSE 7001
// docker-compose.yaml
version: "3"
networks:
api_server_default:
external: trueservices:
hackernewsapp:
networks:
- api_server_default
build:
context: .
dockerfile: Dockerfile
environment:
ENV_NAME: dev
ports:
- 7001:7001
We can now start the application by using docker composer or using docker images:
Start the app by using docker composer:
docker-compose up --build
You can visit the url in browser http://127.0.0.1:7001
now.
Start the app by using docker image:
docker build -t asia.gcr.io/web-campaign/api-server:0.2 .
docker run asia.gcr.io/web-campaign/api-server:0.2
You can visit the url in browser http://127.0.0.1:7001
now.
What’s Next
We will talk about how to automate building docker images in the next article.