wiki:Nodejs

Version 5 (modified by krit, 2 years ago) (diff)

--

Node JS

  1. First, create a new directory where all the files would live. In this directory create a package.json file that describes your app and its dependencies: file package.json as following
    {
      "name": "docker_web_app",
      "version": "1.0.0",
      "description": "Node.js on Docker",
      "author": "First Last <first.last@example.com>",
      "main": "server.js",
      "scripts": {
        "start": "node server.js"
      },
      "dependencies": {
        "express": "^4.16.1"
      }
    }
    

With your new package.json file, run npm install. If you are using npm version 5 or later, this will generate a package-lock.json file which will be copied to your Docker image.

  1. Then, create a server.js file that defines a web app using the Express.js framework:
    'use strict';
    
    const express = require('express');
    
    // Constants
    const PORT = 8080;
    const HOST = '0.0.0.0';
    
    // App
    const app = express();
    app.get('/', (req, res) => {
      res.send('Hello World');
    });
    
    app.listen(PORT, HOST, () => {
      console.log(`Running on http://${HOST}:${PORT}`);
    });
    

3.create Dockerfile with following content

FROM node:16

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .

EXPOSE 8080
CMD [ "node", "server.js" ]
  1. Create a .dockerignore file in the same directory as your Dockerfile with following content:
    node_modules
    npm-debug.log
    

This will prevent your local modules and debug logs from being copied onto your Docker image and possibly overwriting modules installed within your image.