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

Prepare the environment using the instructions provided in the “Preparing the environment” chapter (if you have not done this already).

Please, refer to these helpful resources if the environment has stopped working or instructions in this chapter don’t work:

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/laravel/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/laravel/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/werf-guides $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/laravel/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/laravel/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/werf-guides ~/werf-guide/guides

# Copy the (unchanged) application files to ~/werf-guide/app.
rm -rf ~/werf-guide/app
cp -rf ~/werf-guide/guides/examples/laravel/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/laravel/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 the regular laravel-mix, which is essentially a webpack add-on to bundle all JS, CSS, and media files.

Let’s create a template of an HTML page with the Get image button (it will be accessible at /image):

<!DOCTYPE html>
<html>
<head>
    <title>werf-guide-app</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">

    <link rel="stylesheet" href="{{ URL::asset('css/site.css') }}" />

    <script type="text/javascript" src="{{ URL::asset('js/image.js') }}"></script>
</head>

<body>
<div id="container">
    <button type="button" id="show-image-btn">Get image</button>
</div>
</body>
</html>
<!DOCTYPE html> <html> <head> <title>werf-guide-app</title> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="{{ URL::asset('css/site.css') }}" /> <script type="text/javascript" src="{{ URL::asset('js/image.js') }}"></script> </head> <body> <div id="container"> <button type="button" id="show-image-btn">Get image</button> </div> </body> </html>

Clicking the Get image button must result in an Ajax request that fetches and displays an SVG image:

window.onload=function(){
  var btn = document.getElementById("show-image-btn")
  btn.addEventListener("click", _ => {
      fetch("/images/werf-logo.svg")
        .then((data) => data.text())
        .then((html) => {
          const svgContainer = document.getElementById("container")
          svgContainer.insertAdjacentHTML("beforeend", html)
          var svg = svgContainer.getElementsByTagName("svg")[0]
          svg.setAttribute("id", "image")
          btn.remove()
        }
      )
    }
  )
}
window.onload=function(){ var btn = document.getElementById("show-image-btn") btn.addEventListener("click", _ => { fetch("/images/werf-logo.svg") .then((data) => data.text()) .then((html) => { const svgContainer = document.getElementById("container") svgContainer.insertAdjacentHTML("beforeend", html) var svg = svgContainer.getElementsByTagName("svg")[0] svg.setAttribute("id", "image") btn.remove() } ) } ) }

Our page will also use the resources/css/site.css file.

JS and CSS files as well as an SVG image will be bundled with Webpack and placed to public/... subdirectories:

$ tree public/
public/
├── css
│   ├── app.css
│   └── site.css
├── favicon.ico
├── images
│   └── werf-logo.svg
├── index.php
├── js
│   ├── app.js
│   ├── app.js.LICENSE.txt
│   └── image.js
├── mix-manifest.json
├── robots.txt
└── web.config

Let’s update our routes by adding a new /image endpoint that takes care of the HTML template created above:

<?php

use App\Http\Controllers\PingController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/ping', [PingController::class, 'ping']);

Route::get('/image', function () {
    return view('image');
});
<?php use App\Http\Controllers\PingController; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/ping', [PingController::class, 'ping']); Route::get('/image', function () { return view('image'); });

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

The NGINX container is responsible for serving the 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. Let’s add another stage for building static application files:

...
FROM base as assets

RUN apk add --no-cache nodejs npm

COPY package.json ./
RUN npm install

COPY . .

RUN npm run prod
... FROM base as assets RUN apk add --no-cache nodejs npm COPY package.json ./ RUN npm install COPY . . RUN npm run prod

Copy the built files into the NGINX container:

...
FROM nginx:stable-alpine as frontend
WORKDIR /www

COPY --from=assets /app/public /www

COPY .werf/nginx.conf /etc/nginx/nginx.conf

EXPOSE 8080
... FROM nginx:stable-alpine as frontend WORKDIR /www COPY --from=assets /app/public /www COPY .werf/nginx.conf /etc/nginx/nginx.conf EXPOSE 8080

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:

...
┌ ⛵ image backend
│ ┌ Building stage backend/dockerfile
│ │ backend/dockerfile  Sending build context to Docker daemon  501.2kB
│ │ backend/dockerfile  Step 1/19 : FROM php:8.0-fpm-alpine as base
│ │ backend/dockerfile   ---> 52c511f481c5
...
│ │ backend/dockerfile  Successfully built 1ca8f41e400b
│ │ backend/dockerfile  Successfully tagged 96788dcb-5796-4068-9be4-d5c747184419:latest
│ ├ Info
│ │      name: .../werf-guide-app:2212ff6d5ce7b74c65f7838523ca3aa37be1a4408aca105f907e45bb-1633685776086
│ │        id: 1ca8f41e400b
│ │   created: 2021-10-08 12:36:15 +0300 MSK
│ │      size: 48.8 MiB
│ └ Building stage backend/dockerfile (18.99 seconds)
└ ⛵ image backend (24.49 seconds)

┌ ⛵ image frontend
│ ┌ Building stage frontend/dockerfile
│ │ frontend/dockerfile  Sending build context to Docker daemon  501.2kB
│ │ frontend/dockerfile  Step 1/30 : FROM php:8.0-fpm-alpine as base
│ │ frontend/dockerfile   ---> 52c511f481c5
...
│ │ frontend/dockerfile
│ │ frontend/dockerfile     Laravel Mix v6.0.31
│ │ frontend/dockerfile
│ │ frontend/dockerfile
│ │ frontend/dockerfile  ✔ Compiled Successfully in 6277ms
│ │ frontend/dockerfile  ┌───────────────────────────────────┬───────────┐
│ │ frontend/dockerfile  │                              File │ Size      │
│ │ frontend/dockerfile  ├───────────────────────────────────┼───────────┤
│ │ frontend/dockerfile  │             /images/werf-logo.svg │ 2.67 KiB  │
│ │ frontend/dockerfile  │                      /js/image.js │ 1.3 KiB   │
│ │ frontend/dockerfile  │                      css/site.css │ 160 bytes │
│ │ frontend/dockerfile  └───────────────────────────────────┴───────────┘
│ │ frontend/dockerfile  ✔ Mix: Compiled successfully in 6.36s
│ │ frontend/dockerfile  webpack compiled successfully
...
│ │ frontend/dockerfile  Successfully built 1d182d7f314b
│ │ frontend/dockerfile  Successfully tagged 8b6e9f6c-94d7-4a52-af7c-8a97aaae6e2c:latest
│ ├ Info
│ │      name: .../werf-guide-app:73588c2be51068fa6b336746b8cfe11e890bcf7c00b44b94aaa6cb3e-1633685835794
│ │        id: 1d182d7f314b
│ │   created: 2021-10-08 12:37:15 +0300 MSK
│ │      size: 9.4 MiB
│ └ Building stage frontend/dockerfile (77.50 seconds)
└ ⛵ image frontend (82.38 seconds)

┌ Waiting for release resources to become ready
│ ┌ Status progress
│ │ DEPLOYMENT                                                                                      REPLICAS          AVAILABLE           UP-TO-DATE
│ │ werf-guide-app                                                                                  2->1/1            1                   1
│ │ │   POD                                 READY        RESTARTS          STATUS
│ │ ├── guide-app-645c598898-lfncm          2/2          0                 ContainerCreating ->
│ │ │                                                                      Running
│ │ └── guide-app-c5885499f-n9lm4           2/2          0                 Running -> Terminating
│ └ Status progress
└ Waiting for release resources to become ready (9.32 seconds)

Release "werf-guide-app" has been upgraded. Happy Helming!
NAME: werf-guide-app
LAST DEPLOYED: Fri Oct  8 12:37:34 2021
NAMESPACE: werf-guide-app
STATUS: deployed
REVISION: 13
TEST SUITE: None
Running time 102.90 seconds
... ┌ ⛵ image backend │ ┌ Building stage backend/dockerfile │ │ backend/dockerfile Sending build context to Docker daemon 501.2kB │ │ backend/dockerfile Step 1/19 : FROM php:8.0-fpm-alpine as base │ │ backend/dockerfile ---> 52c511f481c5 ... │ │ backend/dockerfile Successfully built 1ca8f41e400b │ │ backend/dockerfile Successfully tagged 96788dcb-5796-4068-9be4-d5c747184419:latest │ ├ Info │ │ name: .../werf-guide-app:2212ff6d5ce7b74c65f7838523ca3aa37be1a4408aca105f907e45bb-1633685776086 │ │ id: 1ca8f41e400b │ │ created: 2021-10-08 12:36:15 +0300 MSK │ │ size: 48.8 MiB │ └ Building stage backend/dockerfile (18.99 seconds) └ ⛵ image backend (24.49 seconds) ┌ ⛵ image frontend │ ┌ Building stage frontend/dockerfile │ │ frontend/dockerfile Sending build context to Docker daemon 501.2kB │ │ frontend/dockerfile Step 1/30 : FROM php:8.0-fpm-alpine as base │ │ frontend/dockerfile ---> 52c511f481c5 ... │ │ frontend/dockerfile │ │ frontend/dockerfile Laravel Mix v6.0.31 │ │ frontend/dockerfile │ │ frontend/dockerfile │ │ frontend/dockerfile ✔ Compiled Successfully in 6277ms │ │ frontend/dockerfile ┌───────────────────────────────────┬───────────┐ │ │ frontend/dockerfile │ File │ Size │ │ │ frontend/dockerfile ├───────────────────────────────────┼───────────┤ │ │ frontend/dockerfile │ /images/werf-logo.svg │ 2.67 KiB │ │ │ frontend/dockerfile │ /js/image.js │ 1.3 KiB │ │ │ frontend/dockerfile │ css/site.css │ 160 bytes │ │ │ frontend/dockerfile └───────────────────────────────────┴───────────┘ │ │ frontend/dockerfile ✔ Mix: Compiled successfully in 6.36s │ │ frontend/dockerfile webpack compiled successfully ... │ │ frontend/dockerfile Successfully built 1d182d7f314b │ │ frontend/dockerfile Successfully tagged 8b6e9f6c-94d7-4a52-af7c-8a97aaae6e2c:latest │ ├ Info │ │ name: .../werf-guide-app:73588c2be51068fa6b336746b8cfe11e890bcf7c00b44b94aaa6cb3e-1633685835794 │ │ id: 1d182d7f314b │ │ created: 2021-10-08 12:37:15 +0300 MSK │ │ size: 9.4 MiB │ └ Building stage frontend/dockerfile (77.50 seconds) └ ⛵ image frontend (82.38 seconds) ┌ Waiting for release resources to become ready │ ┌ Status progress │ │ DEPLOYMENT REPLICAS AVAILABLE UP-TO-DATE │ │ werf-guide-app 2->1/1 1 1 │ │ │ POD READY RESTARTS STATUS │ │ ├── guide-app-645c598898-lfncm 2/2 0 ContainerCreating -> │ │ │ Running │ │ └── guide-app-c5885499f-n9lm4 2/2 0 Running -> Terminating │ └ Status progress └ Waiting for release resources to become ready (9.32 seconds) Release "werf-guide-app" has been upgraded. Happy Helming! NAME: werf-guide-app LAST DEPLOYED: Fri Oct 8 12:37:34 2021 NAMESPACE: werf-guide-app STATUS: deployed REVISION: 13 TEST SUITE: None Running time 102.90 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 php-fpm (serves dynamic content) and NGINX (serves static content) by increasing the number of replicas in the application’s Deployment.

prev
next