Skip to content

Commit 37a84b6

Browse files
authored
New "Static preset" for websites & single-page apps (#114)
* New "Static" mode following Heroku conventions to support websites & single page apps * Add config use-cases from heroku-buildpack-static to the nginx-static.conf with comments * Improve usage doc flow * Split out static vs proxy docs, improve default doc root & logging * Clarifying documentation * Update changelog * Fix doc typo * Doc formatting * Update to Nginx 1.25.1 & Ruby 3.2.2 * Use buildpack registry name in docs
1 parent de18c06 commit 37a84b6

File tree

11 files changed

+396
-188
lines changed

11 files changed

+396
-188
lines changed

bin/compile

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ echo "-----> nginx-buildpack: Installed ${nginx_version} to app/bin"
2626
# our own copy of Ruby and ensure it's on PATH at runtime.
2727
if ! command -v erb &> /dev/null; then
2828
echo "-----> nginx-buildpack: An existing Ruby installation was not found (required for erb template support)"
29-
ruby_version="3.1.2"
29+
ruby_version="3.2.2"
3030
ruby_url="https://heroku-buildpack-ruby.s3.us-east-1.amazonaws.com/${STACK}/ruby-${ruby_version}.tgz"
3131
vendored_ruby_dir=".heroku-buildpack-nginx/ruby"
3232
mkdir -p "${BUILD_DIR}/${vendored_ruby_dir}"
@@ -50,6 +50,8 @@ cp bin/start-nginx-debug "$BUILD_DIR/bin/"
5050
echo '-----> nginx-buildpack: Added start-nginx-debug to app/bin'
5151
cp bin/start-nginx-solo "$BUILD_DIR/bin/"
5252
echo '-----> nginx-buildpack: Added start-nginx-solo to app/bin'
53+
cp bin/start-nginx-static "$BUILD_DIR/bin/"
54+
echo '-----> nginx-buildpack: Added start-nginx-static to app/bin'
5355

5456
mkdir -p "$BUILD_DIR/config"
5557

bin/start-nginx-static

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#!/usr/bin/env bash
2+
3+
echo 'buildpack=nginx at=erb-interpolate-config'
4+
erb config/nginx.conf.erb > config/nginx.conf
5+
6+
echo 'buildpack=nginx at=nginx-start'
7+
bin/nginx -p . -c config/nginx.conf

changelog.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file.
44
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
55
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
66

7+
## [1.10] - 2023-06-13
8+
### Changes
9+
- New "Static site" preset config
10+
- New `bin/start-nginx-static` to simply start Nginx, its process attached and sending logs to stdout
11+
712
## [1.9] - 2022-06-21
813
### Changes
914
- If a Ruby installation is not found (required for the ERB templating feature), this buildpack will now install its own, to ensure it works on Heroku-22.

config/nginx-static.conf.erb

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
daemon off;
2+
# stay attached to the dyno process, run in Procfile / web
3+
4+
pid /app/nginx.pid;
5+
# /app is $HOME & working directory of Heroku dyno
6+
7+
error_log stderr info;
8+
# As documented for Nginx, but we still see error during start-up in log:
9+
# > nginx: [alert] could not open error log file: open() "./logs/error.log"
10+
11+
worker_processes <%= ENV['NGINX_WORKERS'] || 4 %>;
12+
# Heroku dynos have at least 4 cores.
13+
14+
events {
15+
use epoll;
16+
accept_mutex on;
17+
worker_connections <%= ENV['NGINX_WORKER_CONNECTIONS'] || 1024 %>;
18+
}
19+
20+
http {
21+
gzip on;
22+
gzip_comp_level 2;
23+
gzip_min_length 512;
24+
gzip_proxied any; # Heroku router sends Via header
25+
26+
server_tokens off;
27+
28+
log_format l2met 'measure#nginx.service=$request_time request_id=$http_x_request_id';
29+
access_log /dev/stdout l2met;
30+
# Remote IP, request path, HTTP status, & timestamp are all logged by Heroku Router, so not useful to include here.
31+
32+
include mime.types;
33+
default_type application/octet-stream;
34+
sendfile on;
35+
36+
client_body_timeout <%= ENV['NGINX_CLIENT_BODY_TIMEOUT'] || 5 %>;
37+
# Must read the body in 5 seconds.
38+
39+
server {
40+
listen <%= ENV["PORT"] %>;
41+
server_name _;
42+
keepalive_timeout 5;
43+
client_max_body_size <%= ENV['NGINX_CLIENT_MAX_BODY_SIZE'] || 1 %>M;
44+
45+
## HTTPS Only
46+
if ($http_x_forwarded_proto != "https") {
47+
return 301 https://$host$request_uri;
48+
}
49+
50+
## Document root
51+
root /app/dist;
52+
53+
location / {
54+
## Clean URLs: match on extensionless requests.
55+
# try_files $uri $uri/ $uri.html =404;
56+
57+
## Single-page app client-side routing: returns index.html if the requested path doesn't exist.
58+
## When enabled, the client-side app must handle its own 404 errors.
59+
# error_page 404 = /index.html;
60+
}
61+
62+
## Define specific behaviors for sub directories and other locations.
63+
# location /assets {
64+
# expires 7d;
65+
# }
66+
67+
## Custom error pages
68+
# error_page 404 /404.html;
69+
# error_page 500 /500.html;
70+
}
71+
72+
## Canonical Host: redirect to a canonical hostname.
73+
## Multiple server blocks may be used, one for each hostname to redirect from.
74+
# server {
75+
# server_name some-other-name.example.com;
76+
# return 301 https://canonical-name.example.com$request_uri;
77+
# }
78+
# server {
79+
# server_name yet-another-name.example.com;
80+
# return 301 https://canonical-name.example.com$request_uri;
81+
# }
82+
# …
83+
}

nginx-heroku-18.tgz

98.4 KB
Binary file not shown.

nginx-heroku-20.tgz

165 KB
Binary file not shown.

nginx-heroku-22.tgz

107 KB
Binary file not shown.

proxy.md

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
# Heroku Buildpack: Nginx local proxy to backend app servers
2+
3+
Operates as an HTTP proxy to an app server running in the same dyno, via UNIX domain sockets.
4+
5+
Add this buildpack to an app, as the last buildpack:
6+
```bash
7+
heroku buildpacks:add --app APP_NAME heroku-community/nginx
8+
```
9+
10+
Create the `Procfile` in the root of your app, containing,
11+
```
12+
web: bin/start-nginx <backend server command>
13+
```
14+
Example with backend server command: `bin/start-nginx bundle exec unicorn -c config/unicorn.rb`
15+
16+
Backend server must:
17+
* Listen to the socket at `/tmp/nginx.socket`.
18+
* Touch `/tmp/app-initialized` when the backend is ready for traffic.
19+
20+
The [default config `config/nginx.conf.erb`](config/nginx.conf.erb) will be loaded automatically. To customize, copy the default config to your app source code at `config/nginx.conf.erb`
21+
22+
## Logging
23+
24+
**Proxy mode writes logs to files, which is not the Heroku way. They should go to stdout.**
25+
26+
Nginx will output the following style of logs:
27+
28+
```
29+
measure.nginx.service=0.007 request_id=e2c79e86b3260b9c703756ec93f8a66d
30+
```
31+
32+
You can correlate this id with your Heroku router logs:
33+
34+
```
35+
at=info method=GET path=/ host=salty-earth-7125.herokuapp.com request_id=e2c79e86b3260b9c703756ec93f8a66d fwd="67.180.77.184" dyno=web.1 connect=1ms service=8ms status=200 bytes=21
36+
```
37+
### Setting custom log paths
38+
39+
You can configure custom log paths using the environment variables `NGINX_ACCESS_LOG_PATH` and `NGINX_ERROR_LOG_PATH`.
40+
41+
For example, if you wanted to stop nginx from logging your access logs you could set `NGINX_ACCESS_LOG_PATH` to `/dev/null`:
42+
```bash
43+
$ heroku config:set NGINX_ACCESS_LOG_PATH="/dev/null"
44+
```
45+
46+
## Language/App Server Agnostic
47+
48+
nginx-buildpack provides a command named `bin/start-nginx` this command takes another command as an argument. You must pass your app server's startup command to `start-nginx`.
49+
50+
For example, to get Nginx and Unicorn up and running:
51+
52+
```bash
53+
$ cat Procfile
54+
web: bin/start-nginx bundle exec unicorn -c config/unicorn.rb
55+
```
56+
57+
### Proxy mode nginx-debug
58+
```bash
59+
$ cat Procfile
60+
web: bin/start-nginx-debug bundle exec unicorn -c config/unicorn.rb
61+
```
62+
63+
## Application/Dyno coordination
64+
65+
Proxy mode will not start Nginx until a file has been written to `/tmp/app-initialized`. Since Nginx binds to the dyno's `$PORT` and since the `$PORT` determines if the app can receive traffic, you can delay Nginx accepting traffic until your application is ready to handle it. The [examples below](#example-proxy-setup) show how/when you should write the file when working with Unicorn.
66+
67+
## Force SSL
68+
69+
You can add a redirect/force SSL based on Heroku headers. Full, commented example in the [default config file](config/nginx.conf.erb) or in the [nextjs with forceSSL config file](config/nginx-nextjs-with-forcessl.conf.erb).
70+
71+
```
72+
if ($http_x_forwarded_proto != "https") {
73+
return 301 https://$host$request_uri;
74+
}
75+
```
76+
77+
78+
## Example Proxy Setup
79+
80+
Here are 2 setup examples. One example for a new app, another for an existing app. In both cases, we are working with ruby & unicorn. Keep in mind that this buildpack is not ruby specific. However if your app does happen to use Ruby, make sure to add the Nginx buildpack **after** the Ruby buildpack, so the Nginx buildpack doesn't have to install its own redundant copy of Ruby for the ERB templating feature.
81+
82+
### Existing App
83+
84+
Update Buildpacks to use the latest stable version of this buildpack:
85+
```bash
86+
$ heroku buildpacks:add heroku-community/nginx
87+
```
88+
Alternatively, you can use the Github URL of this repo if you want to edge version.
89+
90+
Update Procfile:
91+
```
92+
web: bin/start-nginx bundle exec unicorn -c config/unicorn.rb
93+
```
94+
```bash
95+
$ git add Procfile
96+
$ git commit -m 'Update procfile for Nginx buildpack'
97+
```
98+
Update Unicorn Config
99+
```ruby
100+
require 'fileutils'
101+
listen '/tmp/nginx.socket'
102+
before_fork do |server,worker|
103+
FileUtils.touch('/tmp/app-initialized')
104+
end
105+
```
106+
```bash
107+
$ git add config/unicorn.rb
108+
$ git commit -m 'Update unicorn config to listen on Nginx socket.'
109+
```
110+
Deploy Changes
111+
```bash
112+
$ git push heroku main
113+
```
114+
115+
### New App
116+
117+
```bash
118+
$ mkdir myapp; cd myapp
119+
$ git init
120+
```
121+
122+
**Gemfile**
123+
```ruby
124+
source 'https://rubygems.org'
125+
gem 'unicorn'
126+
```
127+
128+
**config.ru**
129+
```ruby
130+
run Proc.new {[200,{'Content-Type' => 'text/plain'}, ["hello world"]]}
131+
```
132+
133+
**config/unicorn.rb**
134+
```ruby
135+
require 'fileutils'
136+
preload_app true
137+
timeout 5
138+
worker_processes 4
139+
listen '/tmp/nginx.socket', backlog: 1024
140+
141+
before_fork do |server,worker|
142+
FileUtils.touch('/tmp/app-initialized')
143+
end
144+
```
145+
Install Gems
146+
```bash
147+
$ bundle install
148+
```
149+
Create Procfile
150+
```
151+
web: bin/start-nginx bundle exec unicorn -c config/unicorn.rb
152+
```
153+
Create & Push Heroku App:
154+
```bash
155+
$ heroku create
156+
$ heroku buildpacks:add heroku/ruby
157+
$ heroku buildpacks:add heroku-community/nginx
158+
$ git add .
159+
$ git commit -am "init"
160+
$ git push heroku main
161+
$ heroku logs -t
162+
```
163+
Visit App
164+
```
165+
$ heroku open
166+
```
167+
168+
## Original Motivation
169+
170+
Some application servers (e.g. Ruby's Unicorn) halt progress when dealing with network I/O. Heroku's routing stack [buffers only the headers](https://devcenter.heroku.com/articles/http-routing#request-buffering) of inbound requests. (The router will buffer the headers and body of a response up to 1MB) Thus, the Heroku router engages the dyno during the entire body transfer –from the client to dyno. For applications servers with blocking I/O, the latency per request will be degraded by the content transfer. By using Nginx in front of the application server, we can eliminate a great deal of transfer time from the application server. In addition to making request body transfers more efficient, all other I/O should be improved since the application server need only communicate with a UNIX socket on localhost. Basically, for webservers that are not designed for efficient, non-blocking I/O, we will benefit from having Nginx to handle all I/O operations.
171+
172+
## License
173+
Copyright (c) 2013 Ryan R. Smith
174+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
175+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
176+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

0 commit comments

Comments
 (0)