Objective: To build a Node Express application using Docker images

This project code: Node-express-Docker-sample

Demo :http://yeting-front-node-express-docker-sample.daoapp.io/

Node Express application construction

First, use the Yeomen Express Generator to generate a Node Express application.

The specific operations are described in the Repo above and will not be described here.

It is worth noting:

  • Express exposes PORT 3000 by default, which is modified through the environment variable PORT
  • Start the command node bin/ WWW
  • Debug the gulp command

Dockerfile write

First, select the official Node image as the base image for your project.

FROM node:0.12.7- Wheezy MAINTAINER YeTing "[email protected]"Copy the code

Json is then preferentially copied to the image, preloading third-party dependencies./package.json

WORKDIR /app

COPY ./package.json /app/

RUN npm installCopy the code

Every time Dokcer is successfully built, there will be a cache. This writing method can improve the cache hit ratio and optimize the speed of Docker image building.

Finally, copy the Express application to /app, exposing port 3000.

COPY . /app/

EXPOSE 3000

CMD node bin/www Copy the code

Docker containers communicate with each other through the Link mechanism. EXPOSE 3000 is a prerequisite for other containers to access the port of the Container 3000.

Build the Docker Image

The complete Dockerfile

FROM node:0.12.7-wheezy

MAINTAINER YeTing "[email protected]"

WORKDIR /app

COPY ./package.json /app/

RUN npm install

COPY . /app/

EXPOSE 3000

CMD node bin/www Copy the code

With Dockerfile, we can run the following command to build a front-end image and name it my-express-app:

docker build -t my-express-app .Copy the code

Deploy the Docker Image

Finally, let’s start the container from the image:

docker run -p 80:3000 my-express-appCopy the code

This way we can access our Express application from port 80.

Node Express application performance optimization

Of course, Node is notoriously unstable, and it’s not uncommon for the server to run out of memory and crash out.

We can optimize Express startup commands for this. Introduce the Forever plugin to launch the Express application through Forever.

Dockerfile

FROM node:0.12.7-wheezy

MAINTAINER YeTing "[email protected]"

WORKDIR /app

RUN npm install -g forever

COPY ./package.json /app/

RUN npm install

COPY . /app/

EXPOSE 3000

CMD forever bin/www Copy the code

Very good, we now have a good Express Docker Seed, come and add your logic to finish your Express application.