I use Nginx on my server and want to serve my application on HTTPS using Let's Encrypt certs. I do the following on a fresh server before the application code gets deployed:
Install Nginx
Write the following nginx configuration file to sites-available, for certbot. Then symlink to sites-enabled and restart nginx
server {
listen 80;
server_name foo.bar.com;
allow all;
location ^~ /.well-known/acme-challenge/ {
proxy_pass http://0.0.0.0:22000;
}
}
Then run certbot
certbot certonly -m foo#bar.com --standalone --http-01-port 22000 --preferred-challenges http --cert-name bar.com -d foo.bar.com --agree-tos --non-interactive
All of the above work fine when run manually.
I use Chef to automate the above process. Certbot gets a 404 the first time I deploy. It works on subsequent deployments though.
Keep a note of the following detail:
The phenomenon happens only when I freshly install Nginx and then run my deploy script through Chef and disappears on subsequent deploys.
I use a custom LWRP to run the above steps in Chef expcept nginx installation. Nginx installation is taken care of by chef_nginx. I've pasted the snippet of the LWRP that runs the above steps.
vhost_file = "#{node['certbot']['sites_configuration_path']}/#{node['certbot']['sites_configuration_file']}"
template vhost_file do
cookbook 'certbot'
source 'nginx-letsencrypt.vhost.conf.erb'
owner 'root'
group 'root'
variables(
server_names: new_resource.sans,
certbot_port: node['certbot']['standalone_port'],
mode: node['certbot']['standalone_mode']
)
mode 00644
only_if "test -d #{node['certbot']['sites_configuration_path']}"
end
nginx_site node['certbot']['sites_configuration_file']
Using certbot in standalone mode on port 22000
How do I make things work even on the first deployment ?
Related
I have an NGINX configuration that forwards HTTP to HTTPS. It works fine on my local system and it fails on an AWS EC2.
Here's the only configuration I have added to NGINX, the rest is left intact:
server {
listen 58080;
server_name localhost;
location / {
proxy_pass https://acme.com;
}
}
When serving the content (a single web page UI app) from my laptop everything works as expected. When trying to server the content from AWS I keep seeing errors in the dev-tools console as bellow:
GET https://ec2-*****.compute.amazonaws.com:58080/assets/index.5c112cd8.css net::ERR_SSL_PROTOCOL_ERROR
GET https://ec2-*****.compute.amazonaws.com:58080/assets/index.5660fafb.js net::ERR_SSL_PROTOCOL_ERROR
GET https://ec2-*****.compute.amazonaws.com:58080/favicon.ico net::ERR_SSL_PROTOCOL_ERROR
Something overwrites the protocol from HTTP to HTTPS. I did try just copy-n-paste these links and replace the protocol to HTTP and it works for this link specifically.
I did try adding additional directives such as proxy_set_header Host $proxy_host; and/or changing the server_name _; or the specific host of my EC2 instance but still got the same result.
Both systems env:
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 22.04.1 LTS
Release: 22.04
Codename: jammy
$ nginx -v
nginx version: nginx/1.22.0
I will definitely add a self-signed certificate to NGINX next which I believe it will resolve my issues but I am curious why it works on my localhost while on AWS it does not.
I'm trying to renew an expired certbot SSL for Nginx on Ubuntu 18. I'm getting... well, various weirdness, but the certbot error is:
Certbot failed to authenticate some domains (authenticator: nginx).
The Certificate Authority reported these problems: Domain:
mysite.co.uk Type: connection Detail: ...: Fetching
http://mysite.co.uk/.well-known/acme-challenge/rx6m9QMdK0h16ZOJYsq5sx_AZbxI4zWGvJ6o_kt3b-A:
Connection reset by peer
I've got the site running on HTTP:
server {
listen 80;
listen [::]:80;
server_name www.mysite.co.uk mysite.co.uk;
root /var/www/html;
}
...the nginx.conf is telling it to keep its PID in /run/nginx.pid, I can start and stop it via service nginx start|stop and everything's good:
curl -I http://www.mysite.co.uk/
HTTP/1.1 200 OK
I'm not clear how this /.well-known/acme-challenge/ thing is supposed to be working - there's certainly no such folder in /var/www/html, but I did read that certbot starts it's own server (??) to manage authentication and it's wise to stop your own while renewing.
So, as root, I do:
cat /run/nginx.pid
> 124876
service nginx stop
lsof -i -P -n | grep LISTEN
> nothing on 80 or 443
cat /run/nginx.pid
> file doesn't exist
certbot certonly --nginx
I know there's a certbot renew command but I'm getting the same results with each, so... anyway. It correctly picks up the domain name from the existing conf, prompts me to renew, and eventually spits out the error above. I also see a couple lines added to nginx error.log:
[notice] 125028#125028: signal process started
[error] 125028#125028: invalid PID number "" in "/run/nginx.pid"
Sure enough, nginx is started and is listening on 80 and 443. I didn't start it. It's also got a new PID. If I try service nginx restart, it fails because it's trying to bind to ports that this other (certbot's ??) Nginx process is already using.
At all times, whether via "proper" nginx or this certbot zombie one, my site is happily returning HTTP 200's to external requests. I've never got a "Connection reset by peer" error myself. Even when I manually created a /var/www/html/.well-known/acme-challenge/test file it's always served it fine.
So.. what in the almighty shenannigans is going on? Why is certbot starting an nginx instance it can't see? Why doesn't it stop it? Is it supposed to be creating something in /.well-known/acme-challenge/? Is my nginx instance somehow interfering? What should be happening? What am I doing wrong??
Ok, I still don't understand the weirdness with certbot starting its own nginx and not stopping it and mucking up PIDs and all that... but certbot can now see our server and renew the SSL certs. And after two days of IT swearing blind that it wasn't being blocked by a firewall rule... it was the firewall.
Sigh.
I'm using the gitea versioning system in a docker environment. The gitea used is a rootless type image.
The http port mapping is “8084:3000” and the ssh port mapping is “2224:2222”.
I generated the keys on my Linux host and added the generated public key to my Gitea account.
1.Test environment
Later I created the ssh config file nano /home/campos/.ssh/config :
Host localhost
HostName localhost
User git
Port 2224
IdentityFile ~/.ssh/id_rsa
After finishing the settings i created the myRepo repository and cloned it.
To perform the clone, I changed the url from ssh://git#localhost:2224/campos/myRepo.git to git#localhost:/campos/myRepo.git
To clone the repository I typed: git clone git#localhost:/campos/myRepo.git
This worked perfectly!
2.Production environment
However, when defining a reverse proxy and a domain name, it was not possible to clone the repository.
Before performing the clone, I changed the ssh configuration file:
Host gitea.domain.com
HostName gitea.domain.com
User git
Port 2224
IdentityFile ~/.ssh/id_rsa
Then I tried to clone the repository again:
git clone git#gitea.domain.com:/campos/myRepo.git
A connection refused message was shown:
Cloning into 'myRepo'...
ssh: connect to host gitea.domain.com port 2224: Connection refused
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
I understand the message is because by default the proxy doesn't handle ssh requests.
Searching a bit, some links say to use "stream" in Nginx.
But I still don't understand how to do this configuration. I need to continue accessing my proxy server on port 22 and redirect port 2224 of the proxy to port 2224 of the docker host.
The gitea.conf configuration file i use is as follows:
server {
listen 443 ssl http2;
server_name gitea.domain.com;
# SSL
ssl_certificate /etc/nginx/ssl/mycert_bundle.crt;
ssl_certificate_key /etc/nginx/ssl/mycert.key;
# logging
access_log /var/log/nginx/gitea.access.log;
error_log /var/log/nginx/gitea.error.log warn;
# reverse proxy
location / {
proxy_pass http://192.168.10.2:8084;
include myconfig/proxy.conf;
}
}
# HTTP redirect
server {
listen 80;
server_name gitea.domain.com;
return 301 https://gitea.domain.com$request_uri;
}
3. Redirection in Nginx
I spent several hours trying to understand how to configure Nginx's "stream" feature. Below is what I did.
At the end of the nginx.conf file I added:
stream {
include /etc/nginx/conf.d/stream;
}
In the stream file in conf.d, I added the content below:
upstream ssh-gitea {
server 10.0.200.39:2224;
}
server {
listen 2224;
proxy_pass ssh-gitea;
}
I tested the Nginx configuration and restart your service:
nginx -t && systemctl restart nginx.service
I viewed whether ports 80,443, 22 and 2224 were open on the proxy server.
ss -tulpn
This configuration made it possible to perform the ssh clone of a repository with a domain name.
4. Clone with ssh correctly
After all the settings I made, I understood that it is possible to use the original url ssh://git#gitea.domain.com:2224/campos/myRepo.git in the clone.
When typing the command git clone ssh://git#gitea.domain.com:2224/campos/myRepo.git, it is not necessary to define the config file in ssh.
This link helped me:
https://discourse.gitea.io/t/password-is-required-to-clone-repository-using-ssh/5006/2
In previous messages I explained my solution. So I'm setting this question as solved.
I'm having trouble with consistent service discovery using EC2, AWS, Docker, Consul-Template, Consul, and NGINX.
I have multiple services, each running on it's own EC2 instance. On these instances I run the following containers (in this order):
cAdvisor (monitoring)
node-exporter (monitoring)
Consul (running in agent mode)
Registrator
My service
Custom container running both nginx and consul-template
The custom container has the following Dockerfile:
FROM nginx:1.9
#Install Curl
RUN apt-get update -qq && apt-get -y install curl
#Install Consul Template
RUN curl -L https://github.com/hashicorp/consul-template/releases/download/v0.10.0/consul-template_0.10.0_linux_amd64.tar.gz | tar -C /usr/local/bin --strip-components 1 -zxf -
#Setup Consul Template Files
RUN mkdir /etc/consul-templates
COPY ./app.conf.tmpl /etc/consul-templates/app.conf
# Remove all other conf files from nginx
RUN rm /etc/nginx/conf.d/*
#Default Variables
ENV CONSUL consul:8500
CMD /usr/sbin/nginx -c /etc/nginx/nginx.conf && consul-template -consul=$CONSUL -template "/etc/consul-templates/app.conf:/etc/nginx/conf.d/app.conf:/usr/sbin/nginx -s reload"
The app.conf file looks like this:
{{range services}}
upstream {{.Name}} {
least_conn;{{range service .Name}}
server {{.Address}}:{{.Port}};{{end}}
}
{{end}}
server {
listen 80 default_server;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
location / {
proxy_pass http://cart/cart/;
}
location /cart {
proxy_pass http://cart/cart;
}
{{range services}}
location /api/{{.Name}} {
proxy_read_timeout 180;
proxy_pass http://{{.Name}}/{{.Name}};
}
{{end}}
}
Everything seems to start up perfectly ok, but at some point (which I'm yet to identify) after start up, consul-template seems to return that there are no available servers for a particular service. This means that the upstream section for that service contains no servers, and I end up with this in the logs:
2015/12/04 07:09:34 [emerg] 77#77: no servers are inside upstream in /etc/nginx/conf.d/app.conf:336
nginx: [emerg] no servers are inside upstream in /etc/nginx/conf.d/app.conf:336
2015/12/04 07:09:34 [ERR] (runner) error running command: exit status 1
Consul Template returned errors:
1 error(s) occurred:
* exit status 1
2015/12/04 07:09:34 [DEBUG] (logging) setting up logging
2015/12/04 07:09:34 [DEBUG] (logging) config:
{
"name": "consul-template",
"level": "WARN",
"syslog": false,
"syslog_facility": "LOCAL0"
}
2015/12/04 07:09:34 [emerg] 7#7: no servers are inside upstream in /etc/nginx/conf.d/app.conf:336
nginx: [emerg] no servers are inside upstream in /etc/nginx/conf.d/app.conf:336
After this, NGINX will no longer accept requests.
I'm sure I'm missing something obvious, but I've tied myself in mental knots about the sequence of events etc. What I think might be happening is that NGINX crashes, but because consul-template is still running, the Docker container doesn't restart. I don't actually care if the container itself restarts, or if just NGINX restarts.
Can someone help?
Consul Template will exit once the script it runs after writing returns a non-zero exit code. See here for the documentation.
The documentation suggests to put a || true just after the restart (or reload) command. This will keep Consul Template running independent of the exit code.
You could consider wrapping the restart in its own shell script that first tests the configuration (with nginx -t) before triggering a reload. You could even move the initial start of nginx to this script as it only makes sense to start nginx once the first (valid) configuration has been written?!
I installed Gitlab CE on a dedicated Ubuntu 14.04 server edition with Omnibus package.
Now I would want to install three other virtual hosts next to gitlab.
Two are node.js web applications launched by a non-root user running on two distinct ports > 1024, the third is a PHP web application that need a web server to be launched from.
There are:
a private bower registry running on 8081 (node.js)
a private npm registry running on 8082 (node.js)
a private composer registry (PHP)
But Omnibus listen 80 and doesn't seem to use neither Apache2 or Nginx, thus I can't use them to serve my PHP app and reverse-proxy my two other node apps.
What serving mechanics Gitlab Omnibus uses to listen 80 ?
How should I create the three other virtual hosts to be able to provide the following vHosts ?
gitlab.mycompany.com (:80) -- already in use
bower.mycompany.com (:80)
npm.mycompany.com (:80)
packagist.mycompany.com (:80)
About these
But Omnibus listen 80 and doesn't seem to use neither Apache2 or Nginx [, thus ...].
and #stdob comment :
Did omnibus not use nginx as a web server ??? –
Wich I responded
I guess not because nginx package isn't installed in the system ...
In facts
From Gitlab official docs :
By default, omnibus-gitlab installs GitLab with bundled Nginx.
So yes!
Omnibus package actually uses Nginx !
but it was bundled, explaining why it doesn't require to be installed as dependency from the host OS.
Thus YES! Nginx can, and should be used to serve my PHP app and reverse-proxy my two other node apps.
Then now
Omnibus-gitlab allows webserver access through user gitlab-www which resides
in the group with the same name. To allow an external webserver access to
GitLab, external webserver user needs to be added gitlab-www group.
To use another web server like Apache or an existing Nginx installation you will have to do
the following steps:
Disable bundled Nginx by specifying in /etc/gitlab/gitlab.rb
nginx['enable'] = false
# For GitLab CI, use the following:
ci_nginx['enable'] = false
Check the username of the non-bundled web-server user. By default, omnibus-gitlab has no default setting for external webserver user.
You have to specify the external webserver user username in the configuration!
Let's say for example that webserver user is www-data.
In /etc/gitlab/gitlab.rb set
web_server['external_users'] = ['www-data']
This setting is an array so you can specify more than one user to be added to gitlab-www group.
Run sudo gitlab-ctl reconfigure for the change to take effect.
Setting the NGINX listen address or addresses
By default NGINX will accept incoming connections on all local IPv4 addresses.
You can change the list of addresses in /etc/gitlab/gitlab.rb.
nginx['listen_addresses'] = ["0.0.0.0", "[::]"] # listen on all IPv4 and IPv6 addresses
For GitLab CI, use the ci_nginx['listen_addresses'] setting.
Setting the NGINX listen port
By default NGINX will listen on the port specified in external_url or
implicitly use the right port (80 for HTTP, 443 for HTTPS). If you are running
GitLab behind a reverse proxy, you may want to override the listen port to
something else. For example, to use port 8080:
nginx['listen_port'] = 8080
Similarly, for GitLab CI:
ci_nginx['listen_port'] = 8081
Supporting proxied SSL
By default NGINX will auto-detect whether to use SSL if external_url
contains https://. If you are running GitLab behind a reverse proxy, you
may wish to keep the external_url as an HTTPS address but communicate with
the GitLab NGINX internally over HTTP. To do this, you can disable HTTPS using
the listen_https option:
nginx['listen_https'] = false
Similarly, for GitLab CI:
ci_nginx['listen_https'] = false
Note that you may need to configure your reverse proxy to forward certain
headers (e.g. Host, X-Forwarded-Ssl, X-Forwarded-For, X-Forwarded-Port) to GitLab.
You may see improper redirections or errors (e.g. "422 Unprocessable Entity",
"Can't verify CSRF token authenticity") if you forget this step. For more
information, see:
What's the de facto standard for a Reverse Proxy to tell the backend SSL is used?
https://wiki.apache.org/couchdb/Nginx_As_a_Reverse_Proxy
To go further you can follow the official docs at https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/doc/settings/nginx.md#using-a-non-bundled-web-server
Configuring our gitlab virtual host
Installing Phusion Passenger
We need to install ruby (gitlab run in omnibus with a bundled ruby) globally in the OS
$ sudo apt-get update
$ sudo apt-get install ruby
$ sudo gem install passenger
Recompile nginx with the passenger module
Instead of Apache2 for example, nginx isn't able to be plugged with binary modules on-the-fly. It must be recompiled for each new plugin you want to add.
Phusion passenger developer team worked hard to provide saying, "a bundled nginx version of passenger" : nginx bins compiled with passenger plugin.
So, lets use it:
requirement: we need to open our TCP port 11371 (the APT key port).
$ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 561F9B9CAC40B2F7
$ sudo apt-get install apt-transport-https ca-certificates
creating passenger.list
$ sudo nano /etc/apt/sources.list.d/passenger.list
with these lignes
# Ubuntu 14.04
deb https://oss-binaries.phusionpassenger.com/apt/passenger trusty main
use the right repo for your ubuntu version. For Ubuntu 15.04 for example:
deb https://oss-binaries.phusionpassenger.com/apt/passenger vivid main
Edit permissions:
$ sudo chown root: /etc/apt/sources.list.d/passenger.list
$ sudo chmod 600 /etc/apt/sources.list.d/passenger.list
Updating package list:
$ sudo apt-get update
Allowing it as unattended-upgrades
$ sudo nano /etc/apt/apt.conf.d/50unattended-upgrades
Find or create this config block on top of the file:
// Automatically upgrade packages from these (origin:archive) pairs
Unattended-Upgrade::Allowed-Origins {
// you may have some instructions here
};
Add the following:
// Automatically upgrade packages from these (origin:archive) pairs
Unattended-Upgrade::Allowed-Origins {
// you may have some instructions here
// To check "Origin:" and "Suite:", you could use e.g.:
// grep "Origin\|Suite" /var/lib/apt/lists/oss-binaries.phusionpassenger.com*
"Phusion:stable";
};
Now (re)install nginx-extra and passenger:
$ sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak_"$(date +%Y-%m-%d_%H:%M)"
$ sudo apt-get install nginx-extras passenger
configure it
Uncomment the passenger_root and passenger_ruby directives in the /etc/nginx/nginx.conf file:
$ sudo nano /etc/nginx/nginx.conf
... to obtain something like:
##
# Phusion Passenger config
##
# Uncomment it if you installed passenger or passenger-enterprise
##
passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;
passenger_ruby /usr/bin/passenger_free_ruby;
create the nginx site configuration (the virtual host conf)
$ nano /etc/nginx/sites-available/gitlab.conf
server {
listen *:80;
server_name gitlab.mycompany.com;
server_tokens off;
root /opt/gitlab/embedded/service/gitlab-rails/public;
client_max_body_size 250m;
access_log /var/log/gitlab/nginx/gitlab_access.log;
error_log /var/log/gitlab/nginx/gitlab_error.log;
# Ensure Passenger uses the bundled Ruby version
passenger_ruby /opt/gitlab/embedded/bin/ruby;
# Correct the $PATH variable to included packaged executables
passenger_env_var PATH "/opt/gitlab/bin:/opt/gitlab/embedded/bin:/usr/local/bin:/usr/bin:/bin";
# Make sure Passenger runs as the correct user and group to
# prevent permission issues
passenger_user git;
passenger_group git;
# Enable Passenger & keep at least one instance running at all times
passenger_enabled on;
passenger_min_instances 1;
error_page 502 /502.html;
}
Now we can enable it:
$ sudo ln -s /etc/nginx/sites-available/gitlab.cong /etc/nginx/sites-enabled/
There is no a2ensite equivalent coming natively with nginx, so we use ln, but if you want, there is a project on github:
nginx_ensite:
nginx_ensite and nginx_dissite for quick virtual host enabling and disabling
This is a shell (Bash) script that replicates for nginx the Debian a2ensite and a2dissite for enabling and disabling sites as virtual hosts in Apache 2.2/2.4.
It' done :-). Finally, restart nginx
$ sudo service nginx restart
With this new configuration, you are able to run other virtual hosts next to gitlab to serve what you want
Just create new configs in /etc/nginx/sites-available.
In my case, I made running and serving this way on the same host :
gitlab.mycompany.com - the awesome git platform written in ruby
ci.mycompany.com - the gitlab continuous integration server written in ruby
npm.mycompany.com - a private npm registry written in node.js
bower.mycompany.com - a private bower registry written in node.js
packagist.mycompany.com - a private packagist for composer registry written in php
For example, to serve npm.mycompany.com :
Create a directory for logs:
$ sudo mkdir -p /var/log/private-npm/nginx/
And fill a new vhost config file:
$ sudo nano /etc/nginx/sites-available/npm.conf
With this config
server {
listen *:80;
server_name npm.mycompany.com
client_max_body_size 5m;
access_log /var/log/private-npm/nginx/npm_access.log;
error_log /var/log/private-npm/nginx/npm_error.log;
location / {
proxy_pass http://localhost:8082;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Then enable it and restart it:
$ sudo ln -s /etc/nginx/sites-available/npm.conf /etc/nginx/sites-enabled/
$ sudo service nginx restart
As I would not like to change the nginx server for gitlab (with some other integrations), the safest way would be below solution.
also as per
Gitlab:Ningx =>Inserting custom settings into the NGINX config
edit the /etc/gitlab/gitlab.rb of your gitlab:
nano /etc/gitlab/gitlab.rb
and sroll to nginx['custom_nginx_config'] and modify as below make sure to uncomment
# Example: include a directory to scan for additional config files
nginx['custom_nginx_config'] = "include /etc/nginx/conf.d/*.conf;"
create the new config dir:
mkdir -p /etc/nginx/conf.d/
nano /etc/nginx/conf.d/new_app.conf
and add content to your new config
# my new app config : /etc/nginx/conf.d/new_app.conf
# set location of new app
upstream new_app {
server localhost:1234; # wherever it might be
}
# set the new app server
server {
listen *:80;
server_name new_app.mycompany.com;
server_tokens off;
access_log /var/log/new_app_access.log;
error_log /var/log/new_app_error.log;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
location / { proxy_pass http://new_app; }
}
and reconfigure gitlab to get the new settings inserted
gitlab-ctl reconfigure
to restart nginx
gitlab-ctl restart nginx
to check nginx error log:
tail -f /var/log/gitlab/nginx/error.log