How to Access My Docker Backend Container from the Frontend?

0
3
Asked By TechieExplorer42 On

I'm currently working with Docker and have set up a compose file for both my backend and frontend services. They are on the same network, so they should be able to communicate. Here's a simplified version of my setup:

```yaml
services:
backend:
container_name: domain-backend
build: ./backend
ports:
- "3000:3000"
networks:
- innernetwork
frontend:
container_name: domain-frontend
build: ./frontend
volumes:
- ./frontend/caddy_data:/data
- ./frontend/Caddyfile:/etc/caddy/Caddyfile
ports:
- "80:80"
- "443:443"
networks:
- innernetwork

volumes:
caddy_data:

networks:
innernetwork:
driver: bridge
```

I'm trying to access my backend API from the frontend using several URLs in the format:
- http://localhost:3000/api/people
- http://backend/api/people
- https://backend:3000/api/people
But none of them seem to work. Any advice on how I can get this to function properly?

3 Answers

Answered By DevGuru99 On

You actually don't need to expose the backend port if it's only being accessed within your Docker network. Caddy can proxy requests properly if configured right. Make sure your Caddy server is correctly set up to handle requests to the backend following your Caddyfile setup, and check for any errors in your browser’s console.

TechieExplorer42 -

I’ve fixed the Caddy configuration a little; it works well with HTTP but issues arise with HTTPS due to mixed content. I’ll keep tweaking it!

Answered By DockerDude77 On

It sounds like you're running into network scope issues. Remember, 'localhost' inside your frontend container refers to itself, not the backend. Try using just the service name instead, like http://backend:3000/api/people. This should work since they’re in the same Docker network!

TechieExplorer42 -

Thanks for clarifying that! I guess I was just confused about how the networking works within Docker.

Answered By NetworkNerd88 On

If pinging the backend works from within the frontend container but doesn't in the browser, it could be an issue with how HTTP is being served. Browsers might block mixed content, so try to ensure both frontend and backend use HTTPS if you're accessing over HTTPS, or just use HTTP for both during testing.

TechieExplorer42 -

Ah, that makes sense! I suspect that's why I’m getting the ERR_HTTP2_PROTOCOL_ERROR error. I’ll look into it.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.