How to build and run production NodeJS express server with Docker

  docker, express, node.js

I have a server written in express nodejs framework. and currently it has a app.js as below:

// app.js

const express = require('express');
const connectDB = require('./config/db');
var cors = require('cors');

// routes
const books = require('./routes/api/books');

const app = express();

// Connect Database
connectDB();

// cors
app.use(cors({ origin: true, credentials: true }));

// Init Middleware
app.use(express.json({ extended: false }));

app.get('/', (req, res) => res.send('Hello world!'));

app.get('/health-check',(req,res)=> {
    res.send ("OK");
});

// use Routes
app.use('/api/books', books);

// const port = process.env.PORT || 8080;
const port = 8080;

app.listen(port, () => console.log(`Server running on port ${port}`));

And I run the above server using the following command:

npm run app

How can I make this a production level build and run it?

Can I use below Dockerfile to do it?

FROM node:13.12.0-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . ./
RUN npm run build

# production env
FROM nginx:stable-alpine
COPY --from=build /app/build /usr/share/nginx/html
EXPOSE 8080
CMD ["nginx", "-g", "daemon off;"]

Source: Docker Questions

LEAVE A COMMENT