How to deploy React app with docker and serve -s build
Asked Answered
D

2

8

So far I have build the image and deployed it to AWS EC2. But I want to use

serve -s build

to serve the app in production mode. I did it locally and apparently everything seems to be fine..I get this..

┌──────────────────────────────────────────────────┐ │ │ │ Serving! │ │ │ │ - Local: http://localhost:5000 │ │ - On Your Network: http://192.168.1.91:5000 │ │ │ │ Copied local address to clipboard! │ │ │ └──────────────────────────────────────────────────┘

And the page enters..but the when I try to make a request to the api I get 404.

I wanted to know how does react build works and what do I need to do to put it in production mode. And also, what is the dist folder for?

This is my Dockerfile:

FROM node

#Create app directory
WORKDIR /app

# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

#Install dependencies
RUN npm install
RUN npm install [email protected] -g --silent


#Copy app's source code inside the Docker image
COPY . .

#Expose the app's port
EXPOSE 3000

#Run the app when the container is ran
CMD ["npm", "start""]

Thanks!

Discount answered 23/8, 2020 at 17:20 Comment(0)
R
18

This is my Dockerfile I use when I run it with serve -s build

# pull official base image
FROM node:13.12.0-alpine

# set working directory
WORKDIR /app

# Copies package.json and package-lock.json to Docker environment
COPY package*.json ./

# Installs all node packages
RUN npm install

# Copies everything over to Docker environment
COPY . .

# Build for production.
RUN npm run build --production

# Install `serve` to run the application.
RUN npm install -g serve

# Uses port which is used by the actual application
EXPOSE 5000

# Run application
#CMD [ "npm", "start" ]
CMD serve -s build

I just switch between npm start (debug) and serve (for production).

Riga answered 6/2, 2021 at 0:56 Comment(0)
N
0

Here is my Dockerfile:

FROM node:22-alpine

WORKDIR /app

COPY package*.json yarn.lock ./

RUN yarn global add serve
RUN yarn install

COPY public/ public/
COPY tailwind.config.js tsconfig.json ./
COPY src/ src/

RUN ls -lhat

RUN yarn run build --production

EXPOSE 3000

CMD ["serve", "-s", "build"]

It's based on the answer from geric, but:

  1. It's placing the installation of server in the beginning of the file to maximize cache hit
  2. Avoiding COPY . . because then any little change on current dir would invalidate cache on that line
  3. Because this answer is in 2024, its using a node 22

To build and run:

docker build . -t myimage
docker run -p 5000:3000 myimage

Then I can access it on the browser from http://localhost:5000/ or http://192.168.50.10:5000/ (my IP on my lan)

Notum answered 14/8, 2024 at 12:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.