Web Proxy Using Nginx and Docker
Need SSL or Basic Auth? Standup a proxy in less than 5 minutes using Nginx and Docker.
I needed to secure (basic auth) a mongo-express
instance last night and this little trick with Docker and Nginx blew me away (with how simple it was).
This tutorial assumes you have Docker installed (on Amazon Linux it's as simple as sudo yum install -y docker
).
1. Generate a password file:
You will need to have the htpasswd
command installed; it typically comes bundled with Apache2 Tools.
# Create a new password file called ".htpasswd" with the user "admin"
htpasswd -c .htpasswd admin
# Follow the prompt instructions to set the password.
2. Create the nginx.conf
file:
events {
worker_connections 1024;
}
http {
server {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/passwords;
location / {
proxy_pass http://192.168.1.3:8081;
proxy_redirect off;
}
}
}
Do whatever you need here. I'm going to pretend that I have my mongo-express
instance at the specified address 192.168.1.3:8081
. This is the web accessible address of the thing you are proxying. Because of the way Docker works, you typically can't use localhost within the Docker container because of the isolation (please correct me on this one). We'll secure access to this resource with the password file mentioned in step 1. Don't worry about the location of the password file, we're going to mount that as a Docker volume.
3. Start the Nginx Docker container.
docker run --name proxy-of-some-service \
-d --restart=always \
-v /home/ec2-user/nginx.conf:/etc/nginx/nginx.conf:ro \
-v /etc/proxy-users/.htpasswd:/etc/nginx/passwords:ro \
-p 80:80 \
nginx
Let's break this Docker command down:
- --name proxy-of-some-service: what you want to call this container in Docker. It's could be pink-fluffy-bunny for all Docker cares. You can also omit this; Docker will automatically create a goofy name for the container.
- -d: run as a daemon.
- --restart=always: restart the container if it exits.
- -v /home/ec2-user/nginx.conf:/etc/nginx/nginx.conf:ro: mount the file on the host
/home/ec2-user/nginx.conf
as the file/etc/nginx/nginx.conf
in the Docker container. Thero
option at the end means "read only". - -v /etc/proxy-users/.htpasswd:/etc/nginx/passwords:ro: mount the password file.
- -p 80:80: expose the container port 80 on the host at port 80.
- nginx: this is the container image, which is literally the official Nginx Docker image.
And that's it. You should be able to access the proxied service using Basic Authentication.
Stumbling my way through the great wastelands of enterprise software development.