Pianoman
Pianoman

Reputation: 385

How to reach multiple websites in same docker by URL without having to edit my hosts-file

I have a Windows 11 machine that I use run the Docker Engine. One of my docker containers is an Apache-container with PHP.

I want to run multiple websites in this container. In order to tell Apache which site a user is requesting from the browser, I use a servername entry in my Apache conf files that are copied into the DOcker container.

e.g.:

ServerName site1.docker
ServerName site2.docker

In order to tell my Windows system how to reach the Docker container I edit my Hosts file (c:\windows\system32\drivers\etc\hosts) and add these URLs:

  127.0.0.1 site1.docker site2.docker

However, everytime I add a new site I need to remember to add this URL to the hosts file. Is there a better solution, e.g. some entry in the docker-compose of docker files?

Thank you!

Upvotes: 0

Views: 40

Answers (1)

Chris Becke
Chris Becke

Reputation: 36016

First, services like sslip.io exist. These services maintain wild carded dns that either returns localhost, or an ip of your choice and mean you can use names like http://site1.localtest.me or http://site1.127-0-0-1.sslip.io as aliases for localhost.

Next. A reverse proxy. Add Caddy or Traefik to your compose file. Reverse proxies use the request fields - such as host header - and a set of rules - to determine where the request should be handled.

This example uses Traefik to listen on port 80. Traefik then scans containers for labels to match requests.

services:
  ingress:
    image: traefik:v3.2
    command: |
      --api.insecure
      --providers.docker
    networks:
      - www
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    ports:
      - 80:80
    labels:
      traefik.http.routers.ingress.rule: HostRegexp("traefik.*")
      traefik.http.services.ingress.loadbalancer.server.port: 8080

  web:
    image: nginx:latest
    networks:
      - www
    labels:
      traefik.http.routers.web.rule: HostRegexp("web.*")

networks:
  www:

You can use http://traefik.127-0-0-1.sslip.io or http://web.localtest.me or similar hostnames in the browser.

Traefik (or Caddy) does not have to run in the same compose file - they just need to share a docker network with any services they are handling traffic for.

Upvotes: 0

Related Questions