Traefik101 With Pm 2 NodejsTraefik101 With Pm 2 Nodejs

We all know the classic web servers Apache and Nginx, but try the much newer and amazing Traefik! Traefik is a modern HTTP reverse proxy and load balancer that makes deploying microservices easy. Learn basic deployment of a Node.js app using file-based configuration (without using any Container service like Docker).

Traefik

  • Traefik (pronounced traffic) is a modern HTTP reverse proxy and load balancer that makes deploying microservices easy.
  • Traefik integrates with your existing infrastructure components (Docker, Swarm, Kubernetes, Marathon, Consul, Etcd, Rancher, File) and configures itself automatically and dynamically.
  • Pointing Traefik at your orchestrator should be the only configuration step you need. But we will start with the old ways similar to Nginx file-based configuration (No Docker or Orchestrator) in this tutorial.

Why Traefik?

  • Traefik built-in Let’s Encrypt and supports the automatic renewal of SSL certificates.
  • Traefik automatically enables HTTP/2
  • Prometheus/Grafana can be supported through simple Traefik configuration.
  • Its has many more features in its open-source version itself, which are currently not offered by any other open source web servers.

1. Install Node.js

node -v
# Results: Command 'node' not found, but can be installed

sudo apt update
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash
nvm -v
nvm install --lts
nvm use --lts
nvm alias default node

node -v
# Results: v14.15.5

2. Install PM2 and Configure App

npm -v
# Results: 6.14.11

npm install -g pm2
pm2 -v
# Results: 4.5.4

# Run Node App
npm install
npm build
pm2 start ecosystem.config.js --env production
# or use  pm2 start index.js

3. Install Traefik

# go to https://github.com/containous/traefik/releases and download the latest binary.
# downloading using v2.4.5

wget https://github.com/traefik/traefik/releases/download/v2.4.5/traefik_v2.4.5_linux_amd64.tar.gz

# extract the binary tar -zxvf traefik_${traefik_version}_linux_${arch}.tar.gz
tar -zxvf traefik_v2.4.5_linux_amd64.tar.gz

# check help
./traefik --help

# make executable and move to /usr/local/bin
sudo chmod +x traefik
sudo cp /home/$USER/traefik /usr/local/bin
sudo chown root:root /usr/local/bin/traefik
sudo chmod 755 /usr/local/bin/traefik

# give the traefik binary the ability to bind to privileged ports (80, 443) as non-root
sudo setcap 'cap_net_bind_service=+ep' /usr/local/bin/traefik

# setup traefik user and group and permissions
sudo groupadd -g 321 traefik
sudo useradd -g traefik --no-user-group --home-dir /var/www --no-create-home --shell /usr/sbin/nologin --system --uid 321 traefik
sudo usermod -aG traefik

sudo mkdir /etc/traefik
sudo mkdir /etc/traefik/acme
sudo mkdir /etc/traefik/dynamic
sudo chown -R root:root /etc/traefik
sudo chown -R traefik:traefik /etc/traefik/dynamic /etc/traefik/acme

sudo mkdir /var/log/traefik
sudo touch /var/log/traefik/debug.log
sudo touch /var/log/traefik/access.log
sudo chown traefik:traefik  /var/log/traefik/ /var/log/traefik/access.log  /var/log/traefik/debug.log

4. Configuring Traefik

  • Traefik support multiple configurations providers.
  • The simplest ways is to start with file configuration provider as we do in Nginx
  • File configurations can be done in 2 formats: toml and yaml
  • Create the file /etc/traefik/traefik.toml (main conf file similar to /etc/nginx/nginx.conf in nginx) with the following content
# /etc/traefik/traefik.toml
[log]
  level = "DEBUG"
  filePath = "/var/log/traefik/debug.log"

[accessLog]
  filePath =  "/var/log/traefik/access.log"
  bufferingSize =  100

[providers]
  [providers.file]
    filename = "/etc/traefik/traefik-dynamic.toml"

[api]
  dashboard = true
  debug = true

[entryPoints]
  [entryPoints.web]
    address = ":80"
  [entryPoints.web-secure]
    address = ":443"
  [entryPoints.dashboard]
    address = ":8080"

[certificatesResolvers.sample.acme]
  email = "mymail@example.com"
  storage = "/etc/traefik/acme/acme.json"

  [certificatesResolvers.sample.acme.httpChallenge]
  # used during the challenge
    entryPoint = "web"
  • Create the file /etc/traefik/traefik-dynamic.toml (website conf file similar to /etc/nginx/sites-enabled/example.conf in nginx) with the following content
# /etc/traefik/traefik-dynamic.toml
[http]
  # Redirect to https
  [http.middlewares]
    [http.middlewares.test-redirectscheme.redirectScheme]
      scheme = "https"
    [http.middlewares.auth.basicAuth]
     # generate password hash form cli or online generators like https://www.web2generators.com/apache-tools/htpasswd-generator
      users = [
          "admin:$apr1$npasswordhash"
        ]

  [http.routers]
    # node app
    [http.routers.my-router]
      rule = "Host(`www.example.com`)"
      service = "node-pm2"
      entryPoints = ["web-secure"]
    [http.routers.my-router.tls]
      certResolver = "sample"

    # traefik dashboard
    [http.routers.dashboard]
      rule = "Host(`traefik.example.com`) && (PathPrefix(`/api`) || PathPrefix(`/dashboard`))"
      entryPoints = ["web-secure"]
      service = "api@internal"
      middlewares = ["auth"]
    [http.routers.dashboard.tls]
      certResolver = "sample"

# similar to proxy_pass in nginx, traefik maps services
[http.services]
    [http.services.node-pm2.loadbalancer]
      [[http.services.node-pm2.loadbalancer.servers]]
        url = "http://127.0.0.1:1337"

5. Setup Service

  • create the file /etc/systemd/system/traefik.service with the following content
[Unit]
Description=traefik proxy
After=network-online.target
Wants=network-online.target systemd-networkd-wait-online.service

[Service]
Restart=on-abnormal
; User and group the process will run as.
User=traefik
Group=traefik
; Always set "-root" to something safe in case it gets forgotten in the traefikfile.
ExecStart=/usr/local/bin/traefik --configfile=/etc/traefik/traefik.toml
; Limit the number of file descriptors; see `man systemd.exec` for more limit settings.
LimitNOFILE=1048576
; Use private /tmp and /var/tmp, which are discarded after traefik stops.
PrivateTmp=true
; Use a minimal /dev (May bring additional security if switched to 'true', but it may not work on Raspberry Pi's or other devices, so it has been disabled in this dist.)
PrivateDevices=false
; Hide /home, /root, and /run/user. Nobody will steal your SSH-keys.
ProtectHome=true
; Make /usr, /boot, /etc and possibly some more folders read-only.
ProtectSystem=full
; … except /etc/ssl/traefik, because we want Letsencrypt-certificates there.
;   This merely retains r/w access rights, it does not add any new. Must still be writable on the host!
ReadWriteDirectories=/etc/traefik/acme
; The following additional security directives only work with systemd v229 or later.
; They further restrict privileges that can be gained by traefik. Uncomment if you like.
; Note that you may have to add capabilities required by any plugins in use.
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
  • then run the following commands
sudo chown root:root /etc/systemd/system/traefik.service
sudo chmod 644 /etc/systemd/system/traefik.service
sudo systemctl daemon-reload
sudo systemctl start traefik.service
  • to enable autoboot use this command
sudo systemctl enable traefik.service

# to restart
sudo systemctl restart traefik.service
  • use this command to investigate and check logs
journalctl --boot -u traefik.service

6. Debugging

  • Check the https://www.example.com to access web and https://traefik.example.com/dashboard/ for Traefik dashboard
  • Check logs for any errors with journalctl --boot -u traefik.service. or log files at /var/log/traefik/
  • Check the permissions are correct for all config file with ownership to traefik:traefik
  • Check the iptables-rules as Oracle Cloud servers by default don't have entry in IPTABLES. Add using below code:
sudo iptables -L
sudo iptables-save > ~/iptables-rules
sudo iptables -P INPUT ACCEPT
sudo iptables -P OUTPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -F

Traefik Dashboard

References