In this chapter, you will learn how to work with static files and serve them to the client correctly.

The application described in this chapter is not intended for use in production environments as-is. Note that successful completion of this entire guide is required to create a production-ready application.

Preparing the environment

If you haven’t prepared your environment during previous steps, please, do it using the instructions provided in the “Preparing the environment” chapter.

If your environment has stopped working or instructions in this chapter don’t work, please, refer to these hints:

Is Docker running?

Let’s launch Docker Desktop. It takes some time for this application to start Docker. If there are no errors during the startup process, check that Docker is running and is properly configured:

docker run hello-world

You will see the following output if the command completes successfully:

Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
b8dfde127a29: Pull complete
Digest: sha256:9f6ad537c5132bcce57f7a0a20e317228d382c3cd61edae14650eec68b2b345c
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

Should you have any problems, please refer to the Docker documentation.

Let’s launch the Docker Desktop application. It takes some time for the application to start Docker. If there are no errors during the startup process, then check that Docker is running and is properly configured:

docker run hello-world

You will see the following output if the command completes successfully:

Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
b8dfde127a29: Pull complete
Digest: sha256:9f6ad537c5132bcce57f7a0a20e317228d382c3cd61edae14650eec68b2b345c
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

Should you have any problems, please refer to the Docker documentation.

Start Docker:

sudo systemctl restart docker

Make sure that Docker is running:

sudo systemctl status docker

If the Docker start is successful, you will see the following output:

● docker.service - Docker Application Container Engine
     Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
     Active: active (running) since Thu 2021-06-24 13:05:17 MSK; 13s ago
TriggeredBy: ● docker.socket
       Docs: https://docs.docker.com
   Main PID: 2013888 (dockerd)
      Tasks: 36
     Memory: 100.3M
     CGroup: /system.slice/docker.service
             └─2013888 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock

dockerd[2013888]: time="2021-06-24T13:05:16.936197880+03:00" level=warning msg="Your kernel does not support CPU realtime scheduler"
dockerd[2013888]: time="2021-06-24T13:05:16.936219851+03:00" level=warning msg="Your kernel does not support cgroup blkio weight"
dockerd[2013888]: time="2021-06-24T13:05:16.936224976+03:00" level=warning msg="Your kernel does not support cgroup blkio weight_device"
dockerd[2013888]: time="2021-06-24T13:05:16.936311001+03:00" level=info msg="Loading containers: start."
dockerd[2013888]: time="2021-06-24T13:05:17.119938367+03:00" level=info msg="Loading containers: done."
dockerd[2013888]: time="2021-06-24T13:05:17.134054120+03:00" level=info msg="Daemon has completed initialization"
systemd[1]: Started Docker Application Container Engine.
dockerd[2013888]: time="2021-06-24T13:05:17.148493957+03:00" level=info msg="API listen on /run/docker.sock"

Now let’s check if Docker is available and its configuration is correct:

docker run hello-world

You will see the following output if the command completes successfully:

Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
b8dfde127a29: Pull complete
Digest: sha256:9f6ad537c5132bcce57f7a0a20e317228d382c3cd61edae14650eec68b2b345c
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

Should you have any problems, please refer to the Docker documentation.

Have you restarted the computer after setting up the environment?

Let’s start the minikube cluster we have already configured in the “Preparing the environment” chapter:

minikube start

Set the default Namespace so that you don’t have to specify it every time you invoke kubectl:

kubectl config set-context minikube --namespace=werf-guide-app

You will see the following output if the command completes successfully:

😄  minikube v1.20.0 on Ubuntu 20.04
✨  Using the docker driver based on existing profile
👍  Starting control plane node minikube in cluster minikube
🚜  Pulling base image ...
🎉  minikube 1.21.0 is available! Download it: https://github.com/kubernetes/minikube/releases/tag/v1.21.0
💡  To disable this notice, run: 'minikube config set WantUpdateNotification false'

🔄  Restarting existing docker container for "minikube" ...
🐳  Preparing Kubernetes v1.20.2 on Docker 20.10.6 ...
🔎  Verifying Kubernetes components...
    ▪ Using image gcr.io/google_containers/kube-registry-proxy:0.4
    ▪ Using image k8s.gcr.io/ingress-nginx/controller:v0.44.0
    ▪ Using image registry:2.7.1
    ▪ Using image docker.io/jettech/kube-webhook-certgen:v1.5.1
    ▪ Using image docker.io/jettech/kube-webhook-certgen:v1.5.1
    ▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
🔎  Verifying registry addon...
🔎  Verifying ingress addon...
🌟  Enabled addons: storage-provisioner, registry, default-storageclass, ingress
🏄  Done! kubectl is now configured to use "minikube" cluster and "werf-guide-app" namespace by default

Make sure that the command output contains the following line:

Restarting existing docker container for "minikube"

Its absence means that a new minikube cluster was created instead of using the old one. In this case, repeat all the steps required to install the environment using minikube.

Now run the command in the background PowerShell terminal (do not close its window):

minikube tunnel --cleanup=true

Let’s start the minikube cluster we have already configured in the “Preparing the environment” chapter:

minikube start --namespace werf-guide-app

Set the default Namespace so that you don’t have to specify it every time you invoke kubectl:

kubectl config set-context minikube --namespace=werf-guide-app

You will see the following output if the command completes successfully:

😄  minikube v1.20.0 on Ubuntu 20.04
✨  Using the docker driver based on existing profile
👍  Starting control plane node minikube in cluster minikube
🚜  Pulling base image ...
🎉  minikube 1.21.0 is available! Download it: https://github.com/kubernetes/minikube/releases/tag/v1.21.0
💡  To disable this notice, run: 'minikube config set WantUpdateNotification false'

🔄  Restarting existing docker container for "minikube" ...
🐳  Preparing Kubernetes v1.20.2 on Docker 20.10.6 ...
🔎  Verifying Kubernetes components...
    ▪ Using image gcr.io/google_containers/kube-registry-proxy:0.4
    ▪ Using image k8s.gcr.io/ingress-nginx/controller:v0.44.0
    ▪ Using image registry:2.7.1
    ▪ Using image docker.io/jettech/kube-webhook-certgen:v1.5.1
    ▪ Using image docker.io/jettech/kube-webhook-certgen:v1.5.1
    ▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
🔎  Verifying registry addon...
🔎  Verifying ingress addon...
🌟  Enabled addons: storage-provisioner, registry, default-storageclass, ingress
🏄  Done! kubectl is now configured to use "minikube" cluster and "werf-guide-app" namespace by default

Make sure that the command output contains the following line:

Restarting existing docker container for "minikube"

Its absence means that a new minikube cluster was created instead of using the old one. In this case, repeat all the steps required to install the environment from scratch using minikube.

Did you accidentally delete the application's Namespace?

If you have inadvertently deleted Namespace of the application, you must run the following commands to proceed with the guide:

kubectl create namespace werf-guide-app
kubectl create secret docker-registry registrysecret \
  --docker-server='https://index.docker.io/v1/' \
  --docker-username='<Docker Hub username>' \
  --docker-password='<Docker Hub password>'

You will see the following output if the command completes successfully:

namespace/werf-guide-app created
secret/registrysecret created
Nothing helps; the environment or instructions keep failing.

If nothing worked, repeat all the steps described in the “Preparing the environment” chapter and create a new environment from scratch. If creating an environment from scratch did not help either, please, tell us about your problem in our Telegram chat or create an issue on GitHub. We will be happy to help you!

Preparing the repository

Update the existing repository containing the application:

Run the following commands in PowerShell:

cd ~/werf-guide/app

# To see what changes we will make later in this chapter, let's replace all the application files
# in the repository with new, modified files containing the changes described below.
git rm -r .
cp -Recurse -Force ~/werf-guide/guides/examples/nodejs/030_assets/* .
git add .
git commit -m WIP
What changes we will make
# Enter the command below to show the files we are going to change.
git show --stat
# Enter the command below to show the changes that will be made.
git show

Run the following commands in Bash:

cd ~/werf-guide/app

# To see what changes we will make later in this chapter, let's replace all the application files
# in the repository with new, modified files containing the changes described below.
git rm -r .
cp -rf ~/werf-guide/guides/examples/nodejs/030_assets/. .
git add .
git commit -m WIP
What changes we will make
# Enter the command below to show files we are going to change.
git show --stat
# Enter the command below to show the changes that will be made.
git show

Doesn’t work? Try the instructions on the “I am just starting from this chapter” tab above.

Prepare a new repository with the application:

Run the following commands in PowerShell:

# Clone the example repository to ~/werf-guide/guides (if you have not cloned it yet).
if (-not (Test-Path ~/werf-guide/guides)) {
  git clone https://github.com/werf/website $env:HOMEPATH/werf-guide/guides
}

# Copy the (unchanged) application files to ~/werf-guide/app.
rm -Recurse -Force ~/werf-guide/app
cp -Recurse -Force ~/werf-guide/guides/examples/nodejs/020_logging ~/werf-guide/app

# Make the ~/werf-guide/app directory a git repository.
cd ~/werf-guide/app
git init
git add .
git commit -m initial

# To see what changes we will make later in this chapter, let's replace all the application files
# in the repository with new, modified files containing the changes described below.
git rm -r .
cp -Recurse -Force ~/werf-guide/guides/examples/nodejs/030_assets/* .
git add .
git commit -m WIP
What changes we will make
# Enter the command below to show the files we are going to change.
git show --stat
# Enter the command below to show the changes that will be made.
git show

Run the following commands in Bash:

# Clone the example repository to ~/werf-guide/guides (if you have not cloned it yet).
test -e ~/werf-guide/guides || git clone https://github.com/werf/website ~/werf-guide/guides

# Copy the (unchanged) application files to ~/werf-guide/app.
rm -rf ~/werf-guide/app
cp -rf ~/werf-guide/guides/examples/nodejs/020_logging ~/werf-guide/app

# Make the ~/werf-guide/app directory a git repository.
cd ~/werf-guide/app
git init
git add .
git commit -m initial

# To see what changes we will make later in this chapter, let's replace all the application files
# in the repository with new, modified files containing the changes described below.
git rm -r .
cp -rf ~/werf-guide/guides/examples/nodejs/030_assets/. .
git add .
git commit -m WIP
What changes we will make
# Enter the command below to show files we are going to change.
git show --stat
# Enter the command below to show the changes that will be made.
git show

Adding an /image page to the application

Let’s add a new /image endpoint to our application. It will return a page with a set of static files. We will use webpack to bundle all JS, CSS, and media files.

We will use the dist directory for building static files as well as for storing the index page and the image page:

...
/* GET home page. */
router.get('/', function (req, res, next) {
  res.sendFile(path.resolve(process.cwd(), 'dist', 'index.html'));
});
... /* GET home page. */ router.get('/', function (req, res, next) { res.sendFile(path.resolve(process.cwd(), 'dist', 'index.html')); });
const express = require('express');
const router = express.Router();

/* Image page. */
router.get('/', express.static('dist/image.html'));

module.exports = router;
const express = require('express'); const router = express.Router(); /* Image page. */ router.get('/', express.static('dist/image.html')); module.exports = router;

The application now has a new endpoint called /image in addition to the /ping endpoint we made in previous chapters. This new endpoint displays a page that uses different types of static files.

The commands provided at the beginning of the chapter allow you to view a complete, exhaustive list of the changes made to the application in the current chapter.

Serving static files

A Node.js application can serve static files, e.g., in the express framework, you can make a controller using express.static. However, the authors of express recommend using a server like NGINX to serve static files. This is because the reverse proxy distributes static files much more efficiently than Node.js.

In practice, you can do without the reverse proxy running in front of an application only during development. In addition to efficiently serving static files, the reverse proxy nicely complements the application server by providing many additional features non-implemented at the application server level as well as fast and flexible request routing.

There are several ways to deploy the application server behind the reverse proxy in Kubernetes. We will use a popular and straightforward method that also scales well. As part of it, the NGINX container is deployed to each Pod with the Node.js container. This auxiliary container serves as a proxy for all requests except for static file requests. The NGINX container is responsible for the distribution of static files.

Now, let’s get to the implementation.

Making changes to the build and deploy process

First of all, we have to make changes to the application build process.

Organizing files

We will use webpack to bundle static files. Currently, our application has one index page accessible at /. This page has existed since the start of the project. Its contents are in the /public/index.html file. We will now add another page available at /image. We will also re-structure the /public directory and divide it into two parts: the pages (pages) and the files needed for the pages (assets).

$ tree public
public/
├── assets
│   ├── images
│   │   └── werf-logo.svg
│   ├── javascripts
│   │   ├── image.js
│   │   └── index.js
│   └── stylesheets
│       ├── image.css
│       └── style.css
└── pages
    ├── image.html
    └── index.html

HTML files will act as page templates. We will not cache pages because they are always available at fixed paths (/, /image), and we need to change them occasionally and quickly bring those changes to users. However, asset files will be assembled so that their names will change depending on their contents. This way, you can cache files in a browser for a long time and at the same time easily modify them. Once bundling is complete, you will see the following result in the dist directory (we will show you how to achieve it below):

$ tree dist/
├── css
│   ├── image.40428375b4e566574c8f.css
│   └── index.1e6f9f5ee05a92734053.css
├── image.html
├── index.html
├── js
│   ├── image.e67ef581c6705e6bd9a0.js
│   ├── index.e5a57023092221b727e0.js
│   └── runtime.f9a303951d184e8c1ce3.js
└── media
    └── 2c6aa8e8ef0b96213f30.svg

Building static files

Let’s install the following modules to build and bundle static files:

$ npm install --save-dev \
  webpack webpack-cli webpack-dev-middleware \
  html-webpack-plugin \
  css-loader mini-css-extract-plugin css-minimizer-webpack-plugin
  • webpack, webpack-cli — for building static resources;
  • webpack-dev-middleware — for serving the files emitted from webpack during development;
  • html-webpack-plugin — for generating HTML pages with dynamic assets attaching;
  • css-loader — for using CSS;
  • mini-css-extract-plugin — for extracting CSS into separate files and caching them independently of JS;
  • css-minimizer-webpack-plugin — for optimizing and minifying CSS (it works together with the mode: "production" parameter).

Let’s add a build command to package.json: "build": "webpack" and a request handler for static files if the application is not running in production mode:

...
const app = express();

if (process.env.NODE_ENV != 'production') {
  const webpack = require('webpack');
  const webpackDevMiddleware = require('webpack-dev-middleware');
  const config = require('./webpack.config.js');

  const compiler = webpack(config);

  app.use(
    webpackDevMiddleware(compiler, {
      publicPath: config.output.publicPath,
    })
  );
}
... const app = express(); if (process.env.NODE_ENV != 'production') { const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware'); const config = require('./webpack.config.js'); const compiler = webpack(config); app.use( webpackDevMiddleware(compiler, { publicPath: config.output.publicPath, }) ); }

Let’s make sure that the server runs as expected and static files are being built. For this, assemble static files, run the server, and open the image page in the browser at http://localhost:3000/image:

$ npm run build && npm start
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = {
  mode: 'development',
  devServer: { static: '/dist' },
  devtool: 'inline-source-map',

  // Two entrypoints to collect bundles to. Thus we split CSS and JS between two pages.
  entry: {
    index: path.resolve(__dirname, 'public/assets/javascripts/index.js'),
    image: path.resolve(__dirname, 'public/assets/javascripts/image.js'),
  },

  // Define script paths and the prefix for static files.
  output: {
    filename: 'js/[name].[contenthash].js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
    publicPath: '/static/',
  },

  plugins: [
    // App plugin to extract CSS files.
    new MiniCssExtractPlugin({
      filename: 'css/[name].[contenthash].css',
    }),
    // Generate home page from its template and include only index entry to it including
    // JS and CSS. Thus we avoid including JS and CSS from image page.
    new HtmlWebpackPlugin({
      title: 'werf guide app',
      template: 'public/pages/index.html',
      chunks: ['index'],
    }),
    // The same for the image page, except explicit destination name for the HTML file.
    new HtmlWebpackPlugin({
      title: 'werf logo',
      filename: 'image.html',
      template: 'public/pages/image.html',
      chunks: ['image'],
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
      // Put images to /static/media, the "static" part being defined in "output" settings.
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'media/[contenthash][ext]',
        },
      },
    ],
  },
  // Using optimizations, we extracted runtime JS to separate file to decrese the size of scripts
  // that needs to be loaded in clents browser. Also, we added the minimization of CSS for production.
  optimization: {
    moduleIds: 'deterministic',
    runtimeChunk: 'single',
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all',
        },
      },
    },
    minimizer: [new CssMinimizerPlugin()],
  },
};
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); module.exports = { mode: 'development', devServer: { static: '/dist' }, devtool: 'inline-source-map', // Two entrypoints to collect bundles to. Thus we split CSS and JS between two pages. entry: { index: path.resolve(__dirname, 'public/assets/javascripts/index.js'), image: path.resolve(__dirname, 'public/assets/javascripts/image.js'), }, // Define script paths and the prefix for static files. output: { filename: 'js/[name].[contenthash].js', path: path.resolve(__dirname, 'dist'), clean: true, publicPath: '/static/', }, plugins: [ // App plugin to extract CSS files. new MiniCssExtractPlugin({ filename: 'css/[name].[contenthash].css', }), // Generate home page from its template and include only index entry to it including // JS and CSS. Thus we avoid including JS and CSS from image page. new HtmlWebpackPlugin({ title: 'werf guide app', template: 'public/pages/index.html', chunks: ['index'], }), // The same for the image page, except explicit destination name for the HTML file. new HtmlWebpackPlugin({ title: 'werf logo', filename: 'image.html', template: 'public/pages/image.html', chunks: ['image'], }), ], module: { rules: [ { test: /\.css$/i, use: [MiniCssExtractPlugin.loader, 'css-loader'], }, // Put images to /static/media, the "static" part being defined in "output" settings. { test: /\.(png|svg|jpg|jpeg|gif)$/i, type: 'asset/resource', generator: { filename: 'media/[contenthash][ext]', }, }, ], }, // Using optimizations, we extracted runtime JS to separate file to decrese the size of scripts // that needs to be loaded in clents browser. Also, we added the minimization of CSS for production. optimization: { moduleIds: 'deterministic', runtimeChunk: 'single', splitChunks: { cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendors', chunks: 'all', }, }, }, minimizer: [new CssMinimizerPlugin()], }, };

Deploying static files and the application

Now that we have static files for the NGINX proxy and pages for the application server, we need to distribute static files between containers. The HTML files should end up in the app container, all other files — in the NGINX container.

FROM node:12-alpine as builder
WORKDIR /app

# Copy the files needed to install the application dependencies into the image.
COPY package.json package-lock.json ./

# Install the application dependencies.
RUN npm ci

# Copy all other application files into the image.
COPY . .

# Build static asseets.
RUN npm run build

#############################################################################

FROM node:12-alpine as backend
WORKDIR /app

# Copy the files needed to install the application dependencies into the image.
COPY package.json package-lock.json ./

# Install the application dependencies.
RUN npm ci --production

# Copy app files.
COPY app.js ./
RUN mkdir dist
COPY --from=builder /app/dist/*.html ./dist/
COPY --from=builder /app/bin         ./bin/
COPY --from=builder /app/routes      ./routes/


#############################################################################

# Add an NGINX image with the pre-built assets.
FROM nginx:stable-alpine as frontend
WORKDIR /www

# Copy the pre-built assets from the above image.
COPY --from=builder /app/dist /www/static

# Copy the NGINX configuration.
COPY .werf/nginx.conf /etc/nginx/nginx.conf
FROM node:12-alpine as builder WORKDIR /app # Copy the files needed to install the application dependencies into the image. COPY package.json package-lock.json ./ # Install the application dependencies. RUN npm ci # Copy all other application files into the image. COPY . . # Build static asseets. RUN npm run build ############################################################################# FROM node:12-alpine as backend WORKDIR /app # Copy the files needed to install the application dependencies into the image. COPY package.json package-lock.json ./ # Install the application dependencies. RUN npm ci --production # Copy app files. COPY app.js ./ RUN mkdir dist COPY --from=builder /app/dist/*.html ./dist/ COPY --from=builder /app/bin ./bin/ COPY --from=builder /app/routes ./routes/ ############################################################################# # Add an NGINX image with the pre-built assets. FROM nginx:stable-alpine as frontend WORKDIR /www # Copy the pre-built assets from the above image. COPY --from=builder /app/dist /www/static # Copy the NGINX configuration. COPY .werf/nginx.conf /etc/nginx/nginx.conf

The NGINX config will be added to the NGINX image during the build:

user nginx;
worker_processes 1;
pid /run/nginx.pid;

events {
  worker_connections 1024;
}

http {
  include /etc/nginx/mime.types;
  default_type application/octet-stream;

  upstream backend {
    server 127.0.0.1:3000 fail_timeout=0;
  }

  server {
    listen 80;
    server_name _;

    root /www;

    client_max_body_size 100M;
    keepalive_timeout 10s;

    # For the /static path, assets are delivered directly from the NGINX container file system.
    location /static {
      # Due to the nature of the Webpack's bundling mechanism, the client can keep an asset cache
      # for as long as necessary without worrying about invalidation.
      expires 1y;
      add_header Cache-Control public;
      add_header Last-Modified "";
      add_header ETag "";

      # Serve pre-compressed files if possible (instead of compressing them on the fly).
      gzip_static on;

      access_log off;

      try_files $uri =404;
    }

    # The media assets (pictures, etc.) will also be retrieved from the NGINX container file system,
    # however, we will disable gzip compression for them.
    location /static/media {
      expires 1y;
      add_header Cache-Control public;
      add_header Last-Modified "";
      add_header ETag "";

      access_log off;

      try_files $uri =404;
    }

    # All requests, except for asset requests, are routed to the Node.js backend.
    location / {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host $http_host;
      proxy_redirect off;

      proxy_pass http://backend;
    }
  }
}
user nginx; worker_processes 1; pid /run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; upstream backend { server 127.0.0.1:3000 fail_timeout=0; } server { listen 80; server_name _; root /www; client_max_body_size 100M; keepalive_timeout 10s; # For the /static path, assets are delivered directly from the NGINX container file system. location /static { # Due to the nature of the Webpack's bundling mechanism, the client can keep an asset cache # for as long as necessary without worrying about invalidation. expires 1y; add_header Cache-Control public; add_header Last-Modified ""; add_header ETag ""; # Serve pre-compressed files if possible (instead of compressing them on the fly). gzip_static on; access_log off; try_files $uri =404; } # The media assets (pictures, etc.) will also be retrieved from the NGINX container file system, # however, we will disable gzip compression for them. location /static/media { expires 1y; add_header Cache-Control public; add_header Last-Modified ""; add_header ETag ""; access_log off; try_files $uri =404; } # All requests, except for asset requests, are routed to the Node.js backend. location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://backend; } } }

Now, let’s update werf.yaml so that werf can build two images (backend, frontend) instead of one:

project: werf-guide-app
configVersion: 1

---
image: backend
dockerfile: Dockerfile
target: backend

---
image: frontend
dockerfile: Dockerfile
target: frontend
project: werf-guide-app configVersion: 1 --- image: backend dockerfile: Dockerfile target: backend --- image: frontend dockerfile: Dockerfile target: frontend

Add a new NGINX container to the application Deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: werf-guide-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: werf-guide-app
  template:
    metadata:
      labels:
        app: werf-guide-app
    spec:
      imagePullSecrets:
      - name: registrysecret
      containers:
      - name: backend
        image: {{ .Values.werf.image.backend }}
        command: ["node", "./bin/www"]
        ports:
        - containerPort: 3000
        env:
        - name: NODE_ENV
          value: production
      - name: frontend
        image: {{ .Values.werf.image.frontend }}
        ports:
        - containerPort: 80
apiVersion: apps/v1 kind: Deployment metadata: name: werf-guide-app spec: replicas: 1 selector: matchLabels: app: werf-guide-app template: metadata: labels: app: werf-guide-app spec: imagePullSecrets: - name: registrysecret containers: - name: backend image: {{ .Values.werf.image.backend }} command: ["node", "./bin/www"] ports: - containerPort: 3000 env: - name: NODE_ENV value: production - name: frontend image: {{ .Values.werf.image.frontend }} ports: - containerPort: 80

Service and Ingress should now connect to NGINX’s port 80 instead of 3000. This way, NGINX can serve static files and act as a proxy for application requests:

apiVersion: v1
kind: Service
metadata:
  name: werf-guide-app
spec:
  selector:
    app: werf-guide-app
  ports:
  - name: http
    port: 80
apiVersion: v1 kind: Service metadata: name: werf-guide-app spec: selector: app: werf-guide-app ports: - name: http port: 80
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
  name: werf-guide-app
spec:
  rules:
  - host: werf-guide-app.test
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: werf-guide-app
            port:
              number: 80
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: annotations: kubernetes.io/ingress.class: nginx name: werf-guide-app spec: rules: - host: werf-guide-app.test http: paths: - path: / pathType: Prefix backend: service: name: werf-guide-app port: number: 80

Checking that everything works as expected

Now we have to re-deploy our application:

werf converge --repo <DOCKER HUB USERNAME>/werf-guide-app

You should see the following output:

┌ Concurrent builds plan (no more than 5 images at the same time)
│ Set #0:
│ - ⛵ image backend
│ - ⛵ image frontend
└ Concurrent builds plan (no more than 5 images at the same time)

┌ ⛵ image backend
│ ┌ Building stage backend/dockerfile
│ │ backend/dockerfile  Sending build context to Docker daemon  250.4kB
│ │ backend/dockerfile  Step 1/23 : FROM node:12-alpine as builder
    ...
│ │ backend/dockerfile  Successfully built e946be9a8efb
│ │ backend/dockerfile  Successfully tagged d81cab88-2050-4c42-96c1-206cd16f4e73:latest
│ │ ┌ Store stage into <DOCKER HUB USERNAME>/werf-guide-app
│ │ └ Store stage into <DOCKER HUB USERNAME>/werf-guide-app (18.04 seconds)
│ ├ Info
│ │      name: <DOCKER HUB USERNAME>/werf-guide-app:3b2118a74c218dc86950cfc5c392fd1cf77e99f451e200eb4db8be67-1636714673154
│ │        id: e946be9a8efb
│ │   created: 2022-11-12 13:57:53 +0000 UTC
│ │      size: 30.3 MiB
│ └ Building stage backend/dockerfile (27.87 seconds)
└ ⛵ image backend (35.62 seconds)

┌ ⛵ image frontend
│ ┌ Building stage frontend/dockerfile
│ │ frontend/dockerfile  Sending build context to Docker daemon  250.4kB
│ │ frontend/dockerfile  Step 1/27 : FROM node:12-alpine as builder
    ...
│ │ frontend/dockerfile  Successfully built aca38d642814
│ │ frontend/dockerfile  Successfully tagged 433fb7c7-d9bb-499d-a9fb-7557ad133b67:latest
│ │ ┌ Store stage into <DOCKER HUB USERNAME>/werf-guide-app
│ │ └ Store stage into <DOCKER HUB USERNAME>/werf-guide-app (18.17 seconds)
│ ├ Info
│ │      name: <DOCKER HUB USERNAME>/werf-guide-app:1bdbc7a2dd2038a9e81882ba4e2c4f795543eae30562925e4e4cb4bb-1636714673008
│ │        id: aca38d642814
│ │   created: 2022-11-12 13:57:52 +0000 UTC
│ │      size: 9.4 MiB
│ └ Building stage frontend/dockerfile (27.85 seconds)
└ ⛵ image frontend (35.74 seconds)

┌ Waiting for release resources to become ready
│ ┌ Status progress
│ │ DEPLOYMENT                                                                    REPLICAS      AVAILABLE       UP-TO-DATE
│ │ werf-guide-app                                                                2/1           1               1
│ │ │   POD                          READY      RESTARTS      STATUS              ---
│ │ ├── guide-app-57ff8c54d6-nppmx   0/2        0             ContainerCreating   Waiting for: replicas 2->1                          ↵
│ │
│ │ └── guide-app-d47fd67f9-qln6t    1/1        0             Running
│ └ Status progress
│
│ ┌ Status progress
│ │ DEPLOYMENT                                                                    REPLICAS      AVAILABLE       UP-TO-DATE
│ │ werf-guide-app                                                                2/1           1               1
│ │ │   POD                          READY      RESTARTS      STATUS              ---
│ │ ├── guide-app-57ff8c54d6-nppmx   0/2        0             ContainerCreating   Waiting for: replicas 2->1                          ↵
│ │
│ │ └── guide-app-d47fd67f9-qln6t    1/1        0             Running
│ └ Status progress
│
│ ┌ Status progress
│ │ DEPLOYMENT                                                                    REPLICAS      AVAILABLE       UP-TO-DATE
│ │ werf-guide-app                                                                2->1/1        1               1
│ │ │   POD                          READY      RESTARTS      STATUS
│ │ ├── guide-app-57ff8c54d6-nppmx   2/2        0             ContainerCreating
│ │ │                                                         -> Running
│ │ └── guide-app-d47fd67f9-qln6t    1/1        0             Running ->
│ │                                                           Terminating
│ └ Status progress
└ Waiting for release resources to become ready (10.41 seconds)

Release "werf-guide-app" has been upgraded. Happy Helming!
NAME: werf-guide-app
LAST DEPLOYED: Fri Nov 12 13:58:16 2022
NAMESPACE: werf-guide-app
STATUS: deployed
REVISION: 6
TEST SUITE: None
Running time 51.80 seconds

Go to http://werf-guide-app.test/image in your browser and click on the Get image button. You should see the following output:

Note which resources were requested and which links were used (the last resource here was retrieved via the Ajax request):

Now our application not only provides an API but boasts a set of tools to manage static and JavaScript files effectively.

Furthermore, our application can handle a high load since many requests for static files will not affect the operation of the application as a whole. Note that you can quickly scale Node.js (serves dynamic content) and NGINX (serves static content) by increasing the number of replicas in the application’s Deployment.

prev
next