'Spring Boot CORS issue when connected by angular in docker swarm

I am using angular 13 as a frontend application and spring boot app as backend API server. Both of these projects are containerized and deployed to labs.play-with-docker using docker swarm.

So here is my docker-compose.yml

version: '3.1'

services:
  # Database
  docker_db: 
    image: mysql:8.0
    ports:
      - 3306:3306
    networks:
      - my_network
    volumes:
      - todo_db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=rootpassword
      - MYSQL_USER=user
      - MYSQL_PASSWORD=password
      - MYSQL_DATABASE=my_db
    deploy:
      replicas: 1
  # Backend
  api_server:
    image: <springboot_backend_image>
    ports: 
      - 8080:8080
    environment:
      - MYSQL_HOST=docker_db
    networks:
      - my_network
    depends_on:
      - docker_db
    deploy:
      replicas: 1
  # Frontend
  todo_app:
    image: <angular_frontend_img>
    ports: 
      - 4200:80
    networks:
      - my_network
    depends_on:
      - api_server
    environment:
      - BACKEND_API_URL=host.docker.internal/todos
      - BACKEND_API_PORT=8080
    deploy:
      replicas: 1

networks:
    my_network:
        driver: overlay

volumes:
  todo_db:

In summary, my angular app uses environment variables to pass the backend url&port. However, my angular app faces this CORS issue when trying to send a request to the backend server as shown here firefox console error, request failed error. My docker-compose.yml is working fine when running locally but when using docker swarm with many nodes, this issue appears.

I also try to enable CORS in spring app by adding corsConfiguration class but it still not works

@Configuration
public class CorsConfiguration {
    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
                        .allowedOrigins("*")
                        .allowedHeaders("*")
                        .exposedHeaders("*")
                        .allowCredentials(false);
            }
        };
    }
}

I think I miss something but still not sure what it is. I am still new to docker so I am very appreciated if anyone help me explain along with the solution



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source