I am trying to create a FastAPI app, where I use Traefik to redirect a different URL to the API. I am putting everything in a Docker environment.
Question:
I’m trying to set up a FastAPI app with Traefik to handle requests, using Docker for both services. However, I’m running into an issue where Traefik isn’t resolving the api.localhost
domain properly.
Here’s what I’m trying to achieve:
FastAPI should run on a container, and Traefik should route requests to it.
When I try to access `api.localhost`, I receive the error:
Invoke-WebRequest: The remote name could not be resolved: 'api.localhost'
FastAPI app:
@app.get("/")
def get_status():
return {"status": "running"}
Docker compose:
version: "3.10"
services:
test_api:
build:
context: ./test_api
dockerfile: Dockerfile
env_file:
- .env
ports:
- "3000:3000"
networks:
- "traefik-internal"
labels:
- "traefik.enable=true"
- "traefik.http.routers.api.rule=Host(`api.localhost`)"
- "traefik.http.routers.api.entrypoints=web"
traefik:
image: traefik:latest
command:
- "--api.insecure=true"
- "--providers.docker=true"
- "--entrypoints.web.address=:80"
ports:
- "80:80"
- "8080:8080"
volumes:
# So that Traefik can listen to the Docker events
- /var/run/docker.sock:/var/run/docker.sock
networks:
- "traefik-internal"
networks:
traefik-internal:
name: "traefik-internal"
Problem:
When trying to access http://api.localhost/ via Invoke-WebRequest or a browser, I get the following error:
Invoke-WebRequest: The remote name could not be resolved: 'api.localhost'
What I want to know:
Why can i not access the api using Traefik? Is the request somehow blocked when using the routing by Traefik to the FastAPI? When I get rid of the Traefik services and just try to access localhost:3000/
(where FastAPI app is located), it does work.
Any insights would be greatly appreciated!
What I have tried:
I’ve ensured that the Traefik container is running and listening on port 80
(--entrypoints.web.address=:80
).
I’ve confirmed that the test_api container is running and the FastAPI app is accessible on port 3000
inside the container.
I’ve checked the Traefik dashboard on http://localhost:8080
, and I can see the rule for api.localhost
.
Rens is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
You can use all the hostnames/domains you want in Traefik config, but you also need to make sure that client/browser/apps using the names can resolve those to IP addresses. So you need to have them in DNS or a hosts file.
Within Docker, the Docker DNS will resolve services by their service name like test_api
to the according internal IP. When you use Hosts(`test_api`)
it should work for other containers.