Traefik keycloak docker-compose flutter setup is failing what do I do wrong?

32 Views Asked by At

I have tried multiple tutorials and how-to's so my docker-compose might have a littlebit of everything. Overview: I have a flutter frontend and I want to use a microservices backend with traefik, keycloak as forward auth (later add kubernetes but for local I don't need it) I have added "auth.lab.com" as 127.0.0.1 in etc/hosts so that is actually local I have several problems:

  1. When I try to call my users api (from postman) lets say : "GET http://localhost/api/users/655be5322a7b6614984f1d65" i recieve 404 not found shouldn't traefik given with the host rule find this? (users. api has a basic controller with [Route("api/users")] and [HttpGet("{id}")] , so that shouldn't be an issue)
  2. I get connection rabbitmq failed inside my users and events docker logs (I am guessing it is because the other service endpoints are not found either)
2024-03-04 22:40:08       Connection Failed: rabbitmq://rabbitmq/
2024-03-04 22:40:08       RabbitMQ.Client.Exceptions.BrokerUnreachableException: None of the specified endpoints were reachable
2024-03-04 22:40:08        ---> System.AggregateException: One or more errors occurred. (Connection failed)
2024-03-04 22:40:08        ---> RabbitMQ.Client.Exceptions.ConnectFailureException: Connection failed
2024-03-04 22:40:08        ---> System.Net.Sockets.SocketException (00000001, 11): Resource temporarily unavailable
2024-03-04 22:40:08          at System.Net.Dns.GetHostEntryOrAddressesCore(String hostName, Boolean justAddresses, AddressFamily addressFamily, Nullable`1 startingTimestamp)
2024-03-04 22:40:08          at System.Net.Dns.<>c.<GetHostEntryOrAddressesCoreAsync>b__33_0(Object s, Int64 startingTimestamp)
2024-03-04 22:40:08          at System.Net.Dns.<>c__DisplayClass39_0`1.<RunAsync>b__0(Task <p0>, Object <p1>)
2024-03-04 22:40:08          at System.Threading.Tasks.ContinuationResultTaskFromTask`1.InnerInvoke()
2024-03-04 22:40:08          at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
2024-03-04 22:40:08       --- End of stack trace from previous location ---
2024-03-04 22:40:08          at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
2024-03-04 22:40:08          at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
2024-03-04 22:40:08       --- End of stack trace from previous location ---
2024-03-04 22:40:08          at RabbitMQ.Client.Impl.TcpClientAdapter.ConnectAsync(String host, Int32 port)
2024-03-04 22:40:08          at RabbitMQ.Client.Impl.TaskExtensions.TimeoutAfter(Task task, TimeSpan timeout)
2024-03-04 22:40:08          at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectOrFail(ITcpClient socket, AmqpTcpEndpoint endpoint, TimeSpan timeout)
2024-03-04 22:40:08          --- End of inner exception stack trace ---
2024-03-04 22:40:08          at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectOrFail(ITcpClient socket, AmqpTcpEndpoint endpoint, TimeSpan timeout)
2024-03-04 22:40:08          at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingAddressFamily(AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan timeout, AddressFamily family)
2024-03-04 22:40:08          at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingIPv4(AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan timeout)
2024-03-04 22:40:08          at RabbitMQ.Client.Impl.SocketFrameHandler..ctor(AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout)
2024-03-04 22:40:08          at RabbitMQ.Client.Framing.Impl.IProtocolExtensions.CreateFrameHandler(IProtocol protocol, AmqpTcpEndpoint endpoint, ArrayPool`1 pool, Func`2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout)
2024-03-04 22:40:08          at RabbitMQ.Client.ConnectionFactory.CreateFrameHandler(AmqpTcpEndpoint endpoint)
2024-03-04 22:40:08          at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, Func`2 selector)
2024-03-04 22:40:08          --- End of inner exception stack trace ---
2024-03-04 22:40:08          at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, Func`2 selector)
2024-03-04 22:40:08          at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName)
2024-03-04 22:40:08          --- End of inner exception stack trace ---
2024-03-04 22:40:08          at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName)
2024-03-04 22:40:08          at RabbitMQ.Client.ConnectionFactory.CreateConnection(IList`1 hostnames, String clientProvidedName)
2024-03-04 22:40:08          at MassTransit.RabbitMqTransport.ConnectionContextFactory.CreateConnection(ISupervisor supervisor) in /_/src/Transports/MassTransit.RabbitMqTransport/RabbitMqTransport/ConnectionContextFactory.cs:line 86
  1. I want to use flutter to register and login through keycloak and keycloak act as a forward auth with this function:
Future<void> signInWithAutoCodeExchange(BuildContext context,
      {bool preferEphemeralSession = false}) async {
    try {
      final AuthorizationServiceConfiguration _serviceConfiguration =
          const AuthorizationServiceConfiguration(
        authorizationEndpoint:
            'http://auth.lab.com/auth/realms/myrealm/protocol/openid-connect/auth',
        tokenEndpoint:
            'http://auth.lab.com/auth/realms/myrealm/protocol/openid-connect/token',
        endSessionEndpoint:
            'http://auth.lab.com/auth/realms/myrealm/protocol/openid-connect/logout',
      );

      final AuthorizationTokenResponse? result =
          await appAuth.authorizeAndExchangeCode(
        AuthorizationTokenRequest(
          'MyFlutterApp', // Replace with your actual Keycloak client ID
          'http://localhost:3000/callback', // Replace with your actual redirect URI
          serviceConfiguration: _serviceConfiguration,
          scopes: ['openid', 'profile', 'offline_access'],
          preferEphemeralSession: preferEphemeralSession,
          allowInsecureConnections: false,
        ),
      );

      if (result != null) {
        // Handle successful authentication
        print('Access token: ${result.accessToken}');
        GoRouter.of(context).go(homePath);
      } else {
        // Handle failure
        print('Failed to authenticate');
      }
    } catch (e) {
      // Handle exceptions
      print(e);
    }

but this instead of getting local address over "http://auth.lab.com" it actually opens a real website.. any ideas for this? my docker-compose:

version: '3.4'

services:
  traefik:
    image: "traefik:v2.11"
    hostname: traefik.lab.com
    container_name: "traefik"
    command:
      - "--log.level=DEBUG"
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=true"
      - "--api.dashboard=true"
      - "--entryPoints.web.address=:80"
      - "--entrypoints.web.http.redirections.entrypoint.to=websecure"
      - "--entrypoints.web.http.redirections.entrypoint.scheme=https"
      - "--entryPoints.websecure.address=:443"
    ports:
      - "80:80"
      - "8080:8080"
      - "443:443"
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro"
    networks:
      auth_net:
      service_net:
    labels:
      traefik.enable: true

  mongodb:
    image: mongo:latest
    ports:
      - "27017:27017"
    volumes:
      - mongo-data:/data/db

  events:
    image: ${DOCKER_REGISTRY-}eventsapi
    build:
      context: .
      dockerfile: Events/Events.Api/Dockerfile
    ports:
      - 8082:8082
    environment:
      - "EventBusSettings:HostAddress=amqp://guest:guest@rabbitmq:5672"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.events.rule=PathPrefix(`/api/events`)"
      - "traefik.http.services.events.loadbalancer.server.port=8082"
    networks:
      - service_net
    depends_on:
      - traefik
      - mongodb

  users:
    image: ${DOCKER_REGISTRY-}usersapi
    build:
      context: .
      dockerfile: Users/Users.Api/Dockerfile
    ports:
      - 8083:8083
    environment:
      - "EventBusSettings:HostAddress=amqp://guest:guest@rabbitmq:5672"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.users.rule=PathPrefix(`/api/users`)"
      - "traefik.http.services.users.loadbalancer.server.port=8083"
    networks:
      - service_net
    depends_on:
      - traefik
      - mongodb

  keycloak:
    image: jboss/keycloak
    environment:
      - KEYCLOAK_USER=admin
      - KEYCLOAK_PASSWORD=admin
      - DB_VENDOR=POSTGRES
      - DB_ADDR=keycloakdb
      - DB_DATABASE=keycloak
      - DB_USER=keycloak
      - DB_PASSWORD=keycloak
      - PROXY_ADDRESS_FORWARDING=true
      - KEYCLOAK_LOGLEVEL=INFO
    ports:
      - "8081:8080"
    networks:
      auth_net:
    depends_on:
      - traefik
      - keycloakdb
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.keycloak.rule=Host(`auth.lab.com`)"
      - "traefik.http.routers.keycloak.entrypoints=websecure"
      - "traefik.http.routers.keycloak.tls=true"
      - "traefik.http.services.keycloak.loadbalancer.server.port=8080"

  keycloakdb:
    image: postgres
    environment:
      - POSTGRES_DB=keycloak
      - POSTGRES_USER=keycloak
      - POSTGRES_PASSWORD=keycloak    
    networks:
      auth_net:
    volumes:
      - keycloak_data:/var/lib/postgresql/data

  rabbitmq:
    image: rabbitmq:3.13.0-management
    restart: always
    ports:
      - "5672:5672"
      - "15672:15672"
    networks:
      auth_net:

networks:
  service_net:
  auth_net:

volumes:
  mongo-data:
  keycloak_data:

I also don't have any certificates because I figured for that I would need to have a server for the outside world but I just want to test this locally... although I had tries with openssl self certificates with little to no success

0

There are 0 best solutions below