React + Express on Azure: Invalid Host Header - reactjs

The Error
When deploying to Azure Web Apps with Multi-container support, I receive an "Invalid Host Header" message from https://mysite.azurewebsites.com
Local Setup
This runs fine.
I have two Docker containers: client a React app and server an Express app hosting my API. I am using a proxy to host my API on server.
In client's package.json I have defined:
"proxy": "http://localhost:3001"
I use the following docker compose file to build locally.
version: '2.1'
services:
server:
build: ./server
expose:
- ${APP_SERVER_PORT}
environment:
API_HOST: ${API_HOST}
APP_SERVER_PORT: ${APP_SERVER_PORT}
ports:
- ${APP_SERVER_PORT}:${APP_SERVER_PORT}
volumes:
- ./server/src:/app/project-server/src
command: npm start
client:
build: ./client
environment:
- REACT_APP_PORT=${REACT_APP_PORT}
expose:
- ${REACT_APP_PORT}
ports:
- ${REACT_APP_PORT}:${REACT_APP_PORT}
volumes:
- ./client/src:/app/project-client/src
- ./client/public:/app/project-client/public
links:
- server
command: npm start
Everything runs fine.
On Azure
When deploying to Azure I have the following. client and server images have been stored in Azure Container Registry. They appear to load just fine from the logs.
In my App Service > Container Settings I am loading the images from Azure Container Registry (ACR) and I'm using the following configuration (Docker compose) file.
version: '2.1'
services:
client:
image: <clientimage>.azurecr.io/clientimage:v1
build: ./client
expose:
- 3000
ports:
- 3000:3000
command: npm start
server:
image: <serverimage>.azurecr.io/<serverimage>:v1
build: ./server
expose:
- 3001
ports:
- 3001:3001
command: npm start
I have also defined in Application Settings:
WEBSITES_PORT to be 3000.
This results in the error on my site "Invalid Host Header"
Things I've tried
• Serving the app from the static folder in server. This works in that it serves the app, but it messes up my authentication. I need to be able to serve the static portion from client's App.js and have that talk to my Express API for database calls and authentication.
• In my docker-compose file binding the front end to:
ports:
- 3000:80
• A few other port combinations but no luck.
Also, I think this has something to do with the proxy in client's package.json based on this repo
Any help would be greatly appreciated!
Update
It is the proxy setting.
This somewhat solves it. By removing "proxy": "http://localhost:3001" I am able to load the website, but the suggested answer in the problem does not work for me. i.e. I am now unable to access my API.

Never used azure before and I also don't use a proxy (due to its random connection issues), but if your application is basically running express, you can utilize cors. (As a side note, it's more common to run your express server on 5000 than 3001.)
I first set up an env/config.js folder and file like so:
module.exports = {
development: {
database: 'mongodb://localhost/boilerplate-dev-db',
port: 5000,
portal: 'http://localhost:3000',
},
production: {
database: 'mongodb://localhost/boilerplate-prod-db',
port: 5000,
portal: 'http://example.com',
},
staging: {
database: 'mongodb://localhost/boilerplate-staging-db',
port: 5000,
portal: 'http://localhost:3000',
}
};
Then, depending on the environment, I can implement cors where I'm defining express middleware:
const cors = require('cors');
const config = require('./path/to/env/config.js');
const env = process.env.NODE_ENV;
app.use(
cors({
credentials: true,
origin: config[env].portal,
}),
);
Please note the portal and the AJAX requests MUST have matching host names. For example, if my application is hosted on http://example.com, my front-end API requests must be making requests to http://example.com/api/ (not http://localhost:3000/api/ -- click here to see how I implement it for my website), and the portal env must match the host name http://example.com. This set up is flexible and necessary when running multiple environments.
Or if you're using the create-react-app, then simply eject your app and implement a proxy inside the webpack production configuration.
Or migrate your application to my fullstack boilerplate, which implements the cors example above.

So, I ended up having to move off of containers and serve the React app up in more of a typical MERN architecture with the Express server hosting the React app from the static build folder. I set up some routes with PassportJS to handle my authentication.
Not my preferred solution, I would have preferred to use containers, but this works. Hope this points someone out there in the right direction!

Related

Docker React-.NET 6 Web API Connection Problem

I have a React and .NET 6 project, each in separate containers and brought up together on the same Docker Virtual Network via Docker Compose. Both start and run fine but the React frontend is unable to communicate to the backend.
For whatever reason, I can access the weather api on my backend using my browser (doesn't work on the frontend) but not any other endpoint. https://localhost:5001/api/weatherforecast returns the generated weather data (default tutorial weather api).
But when I go to other endpoints like https://localhost:5001/api/user?userId=1, I get the following: Error: The SSL connection could not be established, see inner exception.
I'm not sure if it is an issue with the setupProxy.js or something wrong with the self-signed cert on the .NET backend.
docker-compose.yml
version: "3.8"
networks:
api-network:
services:
server:
build:
context: ./server-testing/server
args:
PROXY: ${PROXY}
container_name: 'server'
ports:
- '5000:5000'
- '5001:5001'
networks:
- api-network
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_Kestrel__Certificates__Default__Password=${PW}
- ASPNETCORE_Kestrel__Certificates__Default__Path=/https/aspnetapp.pfx
volumes:
- ~/.aspnet/https:/https:ro
client:
build:
context: ./client
args:
PROXY: ${PROXY}
container_name: 'client'
depends_on:
- server
ports:
- '3000:3000'
networks:
- api-network
stdin_open: true # Keep STDIN open even if not attached
tty: true # Allocate a pseudo-TTY
Frontend Setup
The build is served by an nginx layer to serve a production React build.
In my package.json, I have "start": "set HTTPS=true&&react-scripts start" instead of "start": "react-scripts start".
// setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
const context = [
"/api"
];
module.exports = function (app) {
const appProxy = createProxyMiddleware(context, {
target: 'https://server:5001/',
secure: false,
changeOrigin: true
});
app.use(appProxy);
};
Backend Setup
Self-signed certs generated with dotnet dev-certs https -ep %USERPROFILE%\.aspnet\https\aspnetapp.pfx -p { password here }
Three endpoints:
/weatherforecast
/user/
/cart/
Endpoints are accessed as https://localhost:5001/api/endpoint?params
If you need any more information, please let me know. Thanks!

My frontend (REACTJS) doesn't connect with backend(FLASK PYTHON) in docker

I'm trying to dockerize my app. It have an API architecture without using nginx. I'm using this dockerfile for the flask app
FROM python:3.9.0
WORKDIR /ProyectoTitulo
ENV FLASK_APP = app.py
ENV FLASK_ENV = development
COPY ./requirements.txt .
RUN pip install -r requirements.txt
COPY . .
RUN python -m nltk.downloader all
CMD ["python", "app.py"]
This one is my react app dockerfile.
FROM node:16-alpine
WORKDIR /app
COPY ./package.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
Finally this is my docker-compose.yml file
services:
api:
build:
context: .
dockerfile: Dockerfile
image: python-docker
client:
build:
context: .
dockerfile: Dockerfile
image: react-front
ports:
- "3000:3000"
I use build and compose up but when I try to send a HTTP request to and endpoint it says ERR CONNECTION. I need to add something to these files? something to the composer?
One thing is as #bluepuma77 mentioned you need to publish your BE port when that is done and you can locally connect to it you are ready to check the second step.
As I already answered in the SO question similar to your's I will quote my answer here since it will probably be useful to you aswell.
I am no expert on MERN (we mainly run Angular & .Net), but I have to warn you of one thing. We had an issue when setting this up in the beginning as well worked locally in containers but not on our deployment servers because we forgot the basic thing about web applications.
Applications run in your browser, whereas if you deploy an application stack somewhere else, the REST of the services (APIs, DB and such) do not. So referencing your IP/DNS/localhost inside your application won't work, because there is nothing there. A container that contains a WEB application is there to only serve your browser (client) files and then the JS and the logic are executed inside your browser, not the container.
I suspect this might be affecting your ability to connect to the backend.
To solve this you have two options.
Create an HTTP proxy as an additional service and your FE calls that proxy (set up a domain and routing), for instance, Nginx, Traefik, ... and that proxy then can reference your backend with the service name, since it does live in the same environment than API.
Expose the HTTP port directly from the container and then your FE can call remoteServerIP:exposedPort and you will connect directly to the container's interface. (NOTE: I do not recommend this way for real use, only for testing direct connectivity without any proxy)
Well, I think you need to expose the API port, too.
services:
api:
build:
context: .
dockerfile: Dockerfile
image: python-docker
ports:
- "5000:5000" # EXPOSE API
client:
build:
context: .
dockerfile: Dockerfile
image: react-front
ports:
- "3000:3000"

Connect a dockerized app to a database from a remote machine via a VPN connection

I'm currently working on a small app that has to fetch data from a SQL Server DB and push it on the cloud. It works correctly, but I would like to dockerize it to make its deployment easier.
The database is on a private network and I have to use a VPN connection to access it for development (in red in the diagram below). In production, the app will be on a VM in the database's network.
I'm still confused with Docker networks and the --publish option.
Here is my docker-compose file for now.
version: "3.4"
services:
myapp:
build:
context: .
network: host
restart: always
ports:
- "128.1.X.Y:1433:1433"
container_name: myapp
But when I connect to the VPN from my machine (remote) and run my image with this configuration, I get this error:
driver failed programming external connectivity on endpoint myapp (bbb3cc...):
Error starting userland proxy: listen tcp4 128.1.X.Y:1433: bind: cannot assign requested address
Simply "1433:1433" does not work either. The database cannot be accessed. Not really sure about "network: host" either...
Does anyone know what I could be doing wrong?
And another thing I'm wondering is, will the Docker config be the same when I will deploy my container on the VM?
Thank you!

traefik v2 forward domain requests to subroute

I have a react web app built with docker and is behind Traefik proxy. The Docker container has Nginx on port 80 as an HTTP server for the react application. Current config sets http://example.com & https://example.com to react app. I want to forward another domain requests to a subroute of application, for example, forward https://test.example.com requests to https://example.com/test-sub-route. How can I do this with Traefik v2?
Note: The address bar should show https://test.example.com.
This is my current configuration:
version: "3.7"
services:
reactweb:
image: react-web-app:latest
networks:
- 'internal'
- 'traefik'
labels:
- "traefik.enable=true"
- "traefik.docker.network=traefik"
- "traefik.http.routers.reactweb-web.entrypoints=web"
- "traefik.http.routers.reactweb-web.rule=Host(`example.com`)"
- "traefik.http.middlewares.reactweb-redirect.redirectscheme.scheme=https"
- "traefik.http.middlewares.reactweb-redirect.redirectscheme.permanent=true"
- "traefik.http.routers.reactweb-web.middlewares=reactweb-redirect#docker"
- "traefik.http.routers.reactweb-websecure.entrypoints=websecure"
- "traefik.http.routers.reactweb-websecure.rule=Host(`example.com`)"
- "traefik.http.routers.reactweb-websecure.tls=true"
- "traefik.http.services.reactweb-service.loadbalancer.server.port=80"
networks:
traefik:
external: true
internal:
external: false
You can add the prefix in the path in traefik. Use the below code snippet.
labels:
- "traefik.http.middlewares.add-foo.addprefix.prefix=/foo"
Reference: https://docs.traefik.io/middlewares/addprefix/

React not making a request from docker container

so I'm developing a basic Express backend for a React app.
The request is being made like this:
axios.get(`${serverLocation}/api/graph/32`).then(res => {
this.setState({datag: res.data});
for(var key in this.state) {
data.push(this.state[key]);
}
});
Server locations looks like http://IP:PORT.
The api is correct and everything I can see and on my development machine it works. React makes successful requests to the server at specified location etc. The thing is, when I put this into 2 separate docker containers via docker-compose.yml it won't work.
This is my docker-compose.yml:
version: '2.0'
services:
server:
restart: always
container_name: varno_domov_server
build: .
ports:
- "8088:5000"
links:
- react
networks:
- varnodomovnetwork
react:
restart: always
container_name: varno_domov_client
build: client/
ports:
- "8080:3000"
networks:
- varnodomovnetwork
networks:
varnodomovnetwork:
driver: bridge
I also have custom Dockerfiles, the server looking like:
FROM node:10
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 5000
CMD [ "npm", "start" ]
And the client looking like:
FROM node:10
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD [ "npm", "start" ]
If you've made it this far reading, thank you for taking the time. I am open to any suggestions regarding docker here, the React part is not written by me. If any additional information is required, tell me in the comments. Isolation is making me very available :)
So, the thing was that React was submitting requests to the server. I am inexperienced with React, so I was looking for logs in the terminal/bash when they were actually available in the browser to look at.
The problem was, that my server was on a public IP and communicating via HTTP. This meant the browser blocked the content (Mixed Content: The page at was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint), making my graphs display no data. An easy fix is to just make the browser go through with unsafe content, although I am not about that life. So I did the following:
The key problem was that my server and client are 2 separate containers. Therefore, on separate ports. What I've done is edit my nginx configuration to proxy any requests to my domain looking like "https://www.example.come/api" to be forwarded to the port of the server container on the server machine.
Hope this is of any help to someone :)

Resources