deploy a production-ready React app on divio.com (HTTP to HTTPS Redirect on nginx)

The problem: Cloud hosting services such as Divio.com terminate HTTPS already at the loadbalancer level. Your container that hosts react will never receive an incoming HTTPS connection. Still, upgrading HTTP connections to HTTPS connections falls in the responsibility of your container. How to fix that?

Special thanks to Jonathan for his advice and support.

Here is how to build and serve a React app with nginx on divio.com:

Add an nginx/default.conf to your project:

## Redirect HTTP to HTTPS

server {
    # divio sends all traffic to port 80 as HTTPS is terminated already at the load balancer
    listen 80;

    client_max_body_size 20M;

    if ($http_x_forwarded_proto != 'https') {
        return 301 https://$host$request_uri;
    }

    location / {
      alias /usr/share/nginx/html/;
      try_files $uri $uri/ /index.html =404;
    }

}

change your Dockerfile accordingly:

FROM node:16 as builder

# for caching optimisations
COPY package*.json /
RUN yarn install


COPY . /app
WORKDIR /app

ENV PATH=/node_modules/.bin:$PATH

RUN yarn build


FROM nginx:latest
COPY --from=builder /app/build /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx/default.conf /etc/nginx/conf.d

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Update your docker-compose.yml for local support and testing (optional):

# This docker-compose.yml file is used to set up your project in the local
# development environment *only*. It is *not* used in deployment to our cloud
# servers, and has no effect whatsoever in cloud deployments.
#
# See our Developer Handbook for more information:
# http://docs.divio.com/en/latest/reference/docker-docker-compose.html
version: "2.3"

services:
  # The web container is an instance of exactly the same Docker image as your
  # Cloud application container.
  web:
    build:
      context: .
      target: builder
    # Change the port if you'd like to expose your project locally on a
    # different port, for example if you already use port 8000 for
    # something else.
    ports:
     - "8000:80"
    volumes:
      - ".:/app:rw"
    # There is currently a bug: https://github.com/facebook/create-react-app/issues/8688#issuecomment-602149917
    tty: true
    # The default command that the container starts with. If you'd like to run
    # the project locally in Live configuration, you will need to change this.
    # See https://docs.divio.com/en/latest/how-to/local-in-live-mode
    command: yarn start

  nginx:
    build: .
    # Change the port if you'd like to expose your project locally on a
    # different port, for example if you already use port 8000 for
    # something else.
    ports:
     - "8000:80"
    volumes:
      - "./nginx/default.conf:/etc/nginx/conf.d/default.conf"
    command: [nginx-debug, '-g', 'daemon off;']