Why do I get CORS problems between Docker Containers

Viewed 203

I'm creating a small webApp inside of a docker environment. Here's the compose file:

version: '3'
services:
  ## Webserver
  web:
    image: nginx:latest
    depends_on: 
      - mysql
      - php
    volumes:
    - ./www:/var/www/html
    - ./nginx:/etc/nginx/conf.d/
    ports:
    -  "8080:80"
  ## PHP-fpm
  php:
    build: ./php
    volumes:
      - ./www:/var/www/html
      - ./php:/usr/local/etc/php/php.ini
  ## MySQL
  mysql:
    image: mysql:5.7
    restart: always
    environment:
      - MYSQL_DATABASE=db
      - MYSQL_ROOT_PASSWORD=123456
      - MYSQL_USER=user
      - MYSQL_PASSWORD=123456
    ports:
      - "3306:3306"
    volumes:
      - ./mysql:/var/lib/mysql
  ## VUE  Node.js with a vue-cli dev server
  vue:
    build:
      context: ./frontend
      dockerfile: Dockerfile
    ports:
      - "8081:8080"
    volumes:
      - ./frontend:/usr/src/app/my-app
      - /usr/src/app/my-app/node_modules
    stdin_open: true
    tty: true
    environment: 
      - CHOKIDAR_USEPOLLING=true

Connectivity between containers works fine. No Problem with get requests. I know that a non-simple request (like a post request) sends a preflight ('OPTIONS') request aheaed, to check if the origin is allowed by the Server.

For further clarification: request is made from the 'vue' container to the 'web' container

In the index.php file I define the neccessary header. Here's the index.php file (in the 'web' container)

<?php
// error_reporting(E_ALL);
// ini_set('display_errors', '1');



header("Access-Control-Allow-Origin: http://localhost:8081");
header("Access-Control-Allow-Methods: *");



require('route.php');

$router = new Router();
echo $router->handle();

When I send a POST request to the 'web' container I get the following answer:

Access to XMLHttpRequest at 'http://localhost:8080/' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Do I understand the basics of CORS incorrectly? I've been searching a lot and have tried multiple solutions that have been suggested. What am I missing?

(to mention it again: GET requests work fine. So there's no problem with connectivity between containers. The preflight seems to be the crucial point... )

thanks in advance

0 Answers
Related