如何用Traefik+Docker Compose将多子域名绑定到单容器不同端口
Solution for Mapping Multiple Subdomains to Docker Container Ports via Traefik & Docker Compose
Got it, let's set up your subdomains to route to the correct ports on your Docker container using Traefik and Docker Compose. Here's a complete, working configuration tailored to your needs:
version: '3.8' networks: web: external: true # Assumes you've already created this network for Traefik services: my_container: container_name: my_container restart: always build: . networks: - web labels: # Base Traefik configuration - "traefik.backend=my_container" - "traefik.enable=true" - "traefik.docker.network=web" # Route api.mydomain.com to container port 5000 - "traefik.api.frontend.rule=Host:api.mydomain.com" - "traefik.api.port=5000" # Route dl.mydomain.com to container port 5001 - "traefik.dl.frontend.rule=Host:dl.mydomain.com" - "traefik.dl.port=5001" # Route blog.mydomain.com to container port 5002 - "traefik.blog.frontend.rule=Host:blog.mydomain.com" - "traefik.blog.port=5002"
Key Details to Note:
- Named Routers: We use unique prefixes (
traefik.api.,traefik.dl.,traefik.blog.) for each routing rule to avoid conflicts—this lets Traefik distinguish between the different subdomain routes. - Port Mapping: The
traefik.<prefix>.portlabel tells Traefik which port on your container to forward traffic to for each subdomain. - Network: Make sure your Traefik instance is also attached to the
webexternal network (this is standard practice to keep Traefik isolated but connected to your services). - DNS Setup: Don't forget to create A records for each subdomain (
api,dl,blog) pointing to your server's public IP address—without this, the subdomains won't resolve to your container.
Quick Check Before Deploying:
- Confirm the
webnetwork exists (rundocker network lsto verify; if not, create it withdocker network create web). - Ensure your Traefik configuration is set up to listen to Docker labels (most standard Traefik setups include this by default).
内容的提问来源于stack exchange,提问作者mohammad shobeiri
相关产品推荐
相关产品推荐

