10
votes

I have 2 docker containers managed with docker-compose and can't seem to properly use webpack to proxy some request to the backend api.

docker-compose.yml :

version: '2'

services:
  web:
    build:
      context: ./frontend
    ports:
      - "80:8080"
    volumes:
      - ./frontend:/16AGR/frontend:rw
    links:
      - back:back
  back:
    build:
      context: ./backend
    expose:
      - "8080"
    ports:
      - "8081:8080"
    volumes:
      - ./backend:/16AGR/backend:rw

the service web is a simple react application served by a webpack-dev-server. the service back is a node application.

I have no problem to access either app from my host :

$ curl localhost
> index.html
$ curl localhost:8081
> Hello World

I can also ping and curl the back service from the web container :

$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
73ebfef9b250        16agr_web           "npm run start"     37 hours ago        Up 13 seconds       0.0.0.0:80->8080/tcp     16agr_web_1
a421fc24f8d9        16agr_back          "npm start"         37 hours ago        Up 15 seconds       0.0.0.0:8081->8080/tcp   16agr_back_1

$ docker exec -it 73e bash
$ root@73ebfef9b250:/16AGR/frontend# curl back:8080
Hello world

However i have a problem with the proxy. Webpack is started with

webpack-dev-server  --display-reasons --display-error-details --history-api-fallback --progress --colors -d --hot --inline --host=0.0.0.0 --port 8080

and the config file is

frontend/webpack.config.js :

var webpack = require('webpack');
var config = module.exports = {
  ...
  devServer: {
    //redirect api calls to backend server
    proxy: {
      '/api': {
        target: "back:8080",
        secure: false
      }
    }
  }
  ...
}

When i try to request /api/test with a link in my app for exemple i get a generic error, the link and google did not help much :(

[HPM] Error occurred while trying to proxy request /api/test from localhost to back:8080 (EINVAL) (https://nodejs.org/api/errors.html#errors_common_system_errors)

I suspect some weird thing because the proxy is on the container and the request is on localhost but I don't really have an idea to solve this.

1

1 Answers

13
votes

I think I managed to tacle the problem. Just had to change the webpack configuration with the following

  devServer: {
    //redirect api calls to backend server
    proxy: {
      '/api': {
        target: {
          host: "back",
          protocol: 'http:',
          port: 8080
        },
        ignorePath: true,
        changeOrigin: true,
        secure: false
      }
    }
  }