• This repository has been archived on 21/Mar/2024
  • Stars
    star
    137
  • Rank 266,121 (Top 6 %)
  • Language
    Dockerfile
  • License
    MIT License
  • Created over 6 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Instrutctions to buid a frontend Docker image built with Node.js and then served with Nginx. Previously a Docker image.

Build Status

Supported tags and respective Dockerfile links

Node.js frontend development with Chrome Headless tests

This Docker image simplifies the process of creating a full Node.js environment for frontend development with multistage building.

It includes all the dependencies for Puppeteer, so you can just npm install puppeteer and it should work.

It also includes a default Nginx configuration for your frontend application, so in multi-stage Docker builds you can just copy it to an Ngnix "stage" and have an always freshly compiled production ready frontend Docker image for deployment.

It is derivated from this article I wrote:

Angular in Docker with Nginx, supporting configurations / environments, built with multi-stage Docker builds and testing with Chrome Headless

in Medium, and in GitHub

How to use

Previous steps

  • Create your frontend Node.js based code (Angular, React, Vue.js).

  • Create a file .dockerignore (similar to .gitignore) and include in it:

node_modules

...to avoid copying your node_modules to Docker, making things unnecessarily slower.

  • If you want to integrate testing as part of your frontend build inside your Docker image building process (using Chrome Headless via Puppeteer), install Puppeteer locally, so that you can test it locally too and to have it in your development dependencies in your package.json:
npm install --save-dev puppeteer

Dockerfile

  • Create a file Dockerfile based on this image and name the stage build-stage, for building:
# Stage 0, "build-stage", based on Node.js, to build and compile the frontend
FROM tiangolo/node-frontend:10 as build-stage

...
  • Copy your package.json and possibly your package-lock.json:
...

WORKDIR /app

COPY package*.json /app/

...

...just the package*.json files to install all the dependencies once and let Docker use the cache for the next builds. Instead of installing everything after every change in your source code.

  • Install npm packages inside your Dockerfile:
...

RUN npm install

...
  • Copy your source code, it can be TypeScript files, .vue or React with JSX, it will be compiled inside Docker:
...

COPY ./ /app/

...
  • If you have integrated testing with Chrome Headless using Puppeteer, this image comes with all the dependencies for Puppeteer, so, after installing your dependencies (including puppeteer itself), you can just run it. E.g.:
...

RUN npm run test -- --browsers ChromeHeadlessNoSandbox --watch=false

...

...if your tests didn't pass, they will throw an error and your build will stop. So, you will never ship a "broken" frontend Docker image to production.

  • If you need to pass buildtime arguments, for example in Angular, for --configurations, create a default ARG to be used at build time:
...

ARG configuration=production

...
  • Build your source frontend app as you normally would, with npm:
...

RUN npm run build

...
  • If you need to pass build time arguments (for example in Angular), modify the previous instruction using the previously declared ARG, e.g.:
...

RUN npm run build -- --output-path=./dist/out --configuration $configuration

...

...after that, you would have a fresh build of your frontend app code inside a Docker container. But if you are serving frontend (static files) you could serve them with a high performance server as Nginx, and have a leaner Docker image without all the Node.js code.

  • Create a new "stage" (just as if it was another Docker image in the same file) based on Nginx:
...

# Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx
FROM nginx:1.15

...
  • Now you will use the build-stage name created above in the previous "stage", copy the files generated there to the directory that Nginx uses:
...

COPY --from=build-stage /app/dist/out/ /usr/share/nginx/html

...

... make sure you change /app/dist/out/ to the directory inside /app/ that contains your compiled frontend code.

  • This image also contains a default Nginx configuration so that you don't have to provide one. By default it routes everything to your frontend app (to your index.html), so that you can use "HTML5" full URLs and they will always work, even if your users type them directly in the browser. Make your Docker image copy that default configuration from the previous stage to Nginx's configurations directory:
...

COPY --from=build-stage /nginx.conf /etc/nginx/conf.d/default.conf

...
  • Your final Dockerfile could look like:
# Stage 0, "build-stage", based on Node.js, to build and compile the frontend
FROM tiangolo/node-frontend:10 as build-stage

WORKDIR /app

COPY package*.json /app/

RUN npm install

COPY ./ /app/

RUN npm run test -- --browsers ChromeHeadlessNoSandbox --watch=false

ARG configuration=production

RUN npm run build -- --output-path=./dist/out --configuration $configuration


# Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx
FROM nginx:1.15

COPY --from=build-stage /app/dist/out/ /usr/share/nginx/html

COPY --from=build-stage /nginx.conf /etc/nginx/conf.d/default.conf

Building the Docker image

  • To build your shiny new image run:
docker build -t my-frontend-project:prod .

...If you had tests and added above, they will be run. Your app will be compiled and you will end up with a lean high performance Nginx server with your fresh compiled app. Ready for production.

  • If you need to pass build time arguments (like for Angular --configurations), for example if you have a "staging" environment, you can pass them like:
docker build -t my-frontend-project:stag --build-arg configuration="staging" .

Testing the Docker image

  • Now, to test it, run:
docker run -p 80:80 my-frontend-project:prod

...if you are running Docker locally you can now go to http://localhost in your browser and see your frontend.

Tips

  • Develop locally, if you have a live reload server that runs with something like:
npm run start

...use it.

It's faster and simpler to develop locally. But once you think you got it, build your Docker image and try it. You will see how it looks in the full production environment.

  • If you want to have Chrome Headless tests, run them locally first, as you normally would (Karma, Jasmine, Jest, etc). Using the live normal browser. Make sure you have all the configurations right. Then install Puppeteer locally and make sure it runs locally (with local Headless Chrome). Once you know it is running locally, you can add that to your Dockerfile and have "continuous integration" and "continuous building"... and if you want add "continuous deployment". But first make it run locally, it's easier to debug only one step at a time.

  • Have fun.

Advanced Nginx configuration

You can include more Nginx configurations by copying them to /etc/nginx/conf.d/, beside the included Nginx configuration.

By default, this Nginx configuration routes everything to your frontend app (to your index.html). But if you want some specific routes to instead return, for example, an HTTP 404 "Not Found" error, you can include more nginx .conf files in the directory: /etc/nginx/extra-conf.d/.

For example, if you want your final Nginx to send 404 errors to /api and /docs you can create a file `nginx-backend-not-found.conf:

location /api {
    return 404;
}
location /docs {
    return 404;
}

And in your Dockerfile add a line:

COPY ./nginx-backend-not-found.conf /etc/nginx/extra-conf.d/nginx-backend-not-found.conf

Details

These files will be included inside of an "Nginx server directive".

So, you have to put contents that can be included there, like location.


This functionality was made to solve a very specific but common use case:

Let's say you have a load balancer on top of your frontend (and probably backend too), and it sends everything that goes to /api/ to the backend, and /docs to an API documentation site (handled by the backend or other service), and the rest, /, to your frontend.

And your frontend has long-term caching for your main frontend app (as would be normal).

And then at some point, during development or because of a bug, your backend, that serves /docs is down.

You try to go there, but because it's down, your load balancer falls back to what handles /, your frontend.

So, you only see your same frontend instead of the /docs.

Then you check the logs in your backend, you fix it, and try to load /docs again.

But because the frontend had long-term caching, it still shows your same frontend at /docs, even though your backend is back online. Then you have to load it in an incognito window, or fiddle with the local cache of your frontend, etc.

By making Nginx simply respond with 404 errors when requested for /docs, you avoid that problem.

And because you have a load balancer on top, redirecting requests to /docs to the correct service, Nginx would never actually return that 404. Only in the case of a failure, or during development.

License

This project is licensed under the terms of the MIT license.

More Repositories

1

fastapi

FastAPI framework, high performance, easy to learn, fast to code, ready for production
Python
73,897
star
2

full-stack-fastapi-template

Full stack, modern web application template. Using FastAPI, React, SQLModel, PostgreSQL, Docker, GitHub Actions, automatic HTTPS and more.
TypeScript
24,890
star
3

typer

Typer, build great CLIs. Easy to code. Based on Python type hints.
Python
14,943
star
4

sqlmodel

SQL databases in Python, designed for simplicity, compatibility, and robustness.
Python
13,694
star
5

uwsgi-nginx-flask-docker

Docker image with uWSGI and Nginx for Flask applications in Python running in a single container.
Python
2,986
star
6

uvicorn-gunicorn-fastapi-docker

Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python with performance auto-tuning.
Python
2,699
star
7

asyncer

Asyncer, async and await, focused on developer experience.
Python
1,517
star
8

pydantic-sqlalchemy

Tools to convert SQLAlchemy models to Pydantic models
Python
1,173
star
9

nginx-rtmp-docker

Docker image with Nginx using the nginx-rtmp-module module for live multimedia (video) streaming.
Dockerfile
1,110
star
10

dockerswarm.rocks

Docker Swarm mode rocks! Ideas, tools and recipes. Get a production-ready, distributed, HTTPS served, cluster in minutes, not weeks.
Python
1,093
star
11

uwsgi-nginx-docker

Docker image with uWSGI and Nginx for applications in Python (as Flask) in a single container.
Python
646
star
12

uvicorn-gunicorn-docker

Docker image with Uvicorn managed by Gunicorn for high-performance web applications in Python with performance auto-tuning.
Python
628
star
13

full-stack

Full stack, modern web application generator. Using Flask, PostgreSQL DB, Docker, Swagger, automatic HTTPS and more.
Python
523
star
14

meinheld-gunicorn-flask-docker

Docker image with Meinheld and Gunicorn for Flask applications in Python.
Python
486
star
15

full-stack-fastapi-couchbase

Full stack, modern web application generator. Using FastAPI, Couchbase as database, Docker, automatic HTTPS and more.
Python
440
star
16

typer-cli

Run Typer scripts with completion, without having to create a package, using Typer CLI.
Python
367
star
17

poetry-version-plugin

Poetry plugin for dynamically extracting the package version from a __version__ variable or a Git tag.
Python
361
star
18

fastapi-cli

Run and manage FastAPI apps from the command line with FastAPI CLI. 🚀
Python
287
star
19

blog-posts

Blog posts and related code by Sebastián Ramírez (@tiangolo)
Python
273
star
20

uvicorn-gunicorn-starlette-docker

Docker image with Uvicorn managed by Gunicorn for high-performance Starlette web applications in Python with performance auto-tuning.
Python
182
star
21

latest-changes

A GitHub Action to add latest changes after each PR merged automatically
Python
172
star
22

babun-docker

Use Docker Toolbox with Babun (Cygwin) in Windows
Shell
170
star
23

meinheld-gunicorn-docker

Docker image with Meinheld managed by Gunicorn for high-performance WSGI (Flask, Django, etc) web applications in Python with performance auto-tuning.
Python
165
star
24

docker-with-compose

Docker image with Docker Compose installed for CI.
Shell
158
star
25

flask-frontend-docker

Minimal project generator with a Flask backend, a modern frontend (Vue, React or Angular), a Traefik load balancer with HTTPS, all based on Docker.
Vue
130
star
26

python-machine-learning-docker

Docker image with Python 3.6 and 3.7 using Conda, with CUDA variants. To serve as base image for Machine Learning projects.
Dockerfile
84
star
27

uvicorn-gunicorn-machine-learning-docker

Docker image for high-performance Machine Learning web applications. With Uvicorn managed by Gunicorn in Python 3.7 and 3.6, using Conda, with CUDA and TensorFlow variants.
Python
67
star
28

issue-manager

Automatically close issues that have a label, after a custom delay, if no one replies back.
Python
62
star
29

full-stack-flask-couchbase

Full stack, modern web application generator. Using Flask, Couchbase as database, Docker, Swagger, automatic HTTPS and more.
Python
59
star
30

label-approved

Label a Pull Request after a number of approvals
Python
34
star
31

full-stack-flask-couchdb

Full stack, modern web application generator. Using Flask, CouchDB as database, Docker, Swagger, automatic HTTPS and more.
Python
31
star
32

tiangolo

16
star
33

github-actions-sandbox

Not useful for you. It's just a sandbox GitHub repo for me to try out stuff and develop GitHub Actions.
Python
16
star
34

tiangolo.com

Python
16
star
35

docker-auto-labels

Generate each Docker constraint label in random nodes in the cluster.
Python
15
star
36

angular-docker-multi-stage-example

Angular in Docker with Nginx, supporting environments, built with multi-stage Docker builds
15
star
37

ngx-http-client

Angular (4.3+) HttpClientModule with parameter encodings compatible with back ends (Node.js, Python, PHP, etc)
TypeScript
11
star
38

compose-to-rancher

Convert Docker Compose V2 to Rancher compatible Docker Compose V1
Python
10
star
39

markdown-include-variants

Markdown extension to expand directives to include source example files to also include their variants. Only useful to tiangolo's projets. Don't use it. 😅
Python
9
star
40

wunderlist2csv

Convert from Wunderlist backup json file to a CSV file importable by TaskCoach
Python
6
star
41

anaconda_cluster_install

Automatically Install Anaconda Python in a cluster of machines, for a specified user.
Shell
5
star
42

bitbucket_issues_to_redmine_csv

Python
3
star