dockerreverse-proxycaddy

how can I reverse proxy request to server using caddy


I am implementing reverse proxy using caddy in docker container. i have docker-compose file in which i specifed three service caddy, nginx, httpd. i also configured caddyfile in which i redirected my request to servers. when i run '$docker-compose up' all the containers working perfectlly fine. but when i go to

http://localhost/   -   show blank white page
http://localhost:8080/    -   this site cant be reach
http://localhost:8081/    -   this site cant be reach
nginx_container_IP    -   show nginx page
httpd_container_IP    -   show httpd page 

docker-compose.yaml

version: '3'
services:
  proxy:
    image: caddy:2.3.0-alpine
    ports:
      - "80:80"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile
  service1:
    image: nginx:latest
    expose:
      - "8080"
  service2:
    image: httpd:latest
    expose:
      - "8081"

Caddyfile

hostname:80 {
    reverse_proxy service1:8080
    reverse_proxy service2:8081
}

Caddy container logs

{"level":"info","ts":1675247772.029432,"msg":"using provided configuration","config_file":"/etc/caddy/Caddyfile","config_adapter":"caddyfile"} {"level":"info","ts":1675247772.033348,"logger":"admin","msg":"admin endpoint started","address":"tcp/localhost:2019","enforce_origin":false,"origins":["localhost:2019","[::1]:2019","127.0.0.1:2019"]} {"level":"info","ts":1675247772.033649,"logger":"http","msg":"server is listening only on the HTTP port, so no automatic HTTPS will be applied to this server","server_name":"srv0","http_port":80} {"level":"info","ts":1675247772.0337453,"logger":"tls.cache.maintenance","msg":"started background certificate maintenance","cache":"0xc0002f52d0"} {"level":"info","ts":1675247772.0342908,"logger":"tls","msg":"cleaned up storage units"} {"level":"info","ts":1675247772.034485,"msg":"autosaved config","file":"/config/caddy/autosave.json"} {"level":"info","ts":1675247772.0345104,"msg":"serving initial configuration"}

I want that when i request to localhost my request should be forwarded to nginx and httpd backend servers.


Solution

  • Change your Caddyfile to

    localhost:80 {
        reverse_proxy service1:8080
    }
    

    to get http://localhost/ to show the nginx site.

    You will probably want to work with subdomains or paths to make both httpd or nginx accessible:

    nginx.localhost:80 {
        reverse_proxy service1:8080
    }
    httpd.localhost:80 {
        reverse_proxy service2:8081
    }
    

    or

    localhost:80 {
        reverse_proxy /nginx service1:8080
        reverse_proxy /httpd service2:8081
    }
    

    Which would then allow requests such as http://nginx.localhost or http://localhost/nginx.