Redirecting Subdomains to docker containers in same server
Introduction
Article on how to have multiple running docker containers (or any other web servers) and have separate subdomains which map to these services.
Requirements
- A Linux machine on which you have docker containers running
- SSH access to this Linux machine.
- DNS management access.
Steps
- Start by installing a tool to manage a reverse proxy. nginx is a really good option.
sudo apt install nginx
-
Ensure that you can access your docker containers locally using curl/wget command.
-
Start running your services or docker containers to which you want to route traffic
cd <your_project_folder>
docker-compose up # or whatever other command you have assigned to start your server.
- Find the port in which your container or services re running. Double check and ensure that the API is working fine in localhost, using the following commands
ss -lntp # check that the correct port is exposed.
curl localhost:PORT # verify that you get the expected response.
- Decide on the subdomains to which you want to route traffic and add them using your dns management console
Here’s an example image using cloudflare
Note: You can get the public IP of your server using the following curl
command
curl ipinfo.io/ip
- Once you add a subdomain in cloudflare, the next step is to ask nginx to route traffic from these subdomains to the docker services. This can be achieved by the following configuration in
/etc/nginx/nginx.conf
http {
server {
listen 80; # replace with the line below if ssl support is added
# listen 443 ssl;
server_name subdomain.your-domain.com;
# ssl_certificate /etc/letsencrypt/live/subdomain.domain.com/fullchain.pem;
# ssl_certificate_key /etc/letsencrypt/live/subdomain.domain.com/privkey.pem;
location / {
proxy_pass http://localhost:9000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
The ssl_certificate fields are optional and need to be added only if you want to add https in your subdomain. For more details on adding SSL to your subdomain using certbot
, checkout this link.
Alright, that’s it. Now you can navigate to http:<you_subdomain>.<your_domain_with_tld> to access your API.
You can add multiple subdomains and add other server blocks like above in nginx.conf file.
Tada✨