Docker container to generate a React build

Tiempo de lectura: < 1 minuto

Hello, today I’m going to share a very useful container for generating a React build. It already contains everything needed to generate it. Additionally, it is compatible with Vite.js.

The first thing we are going to do is create the file docker-compose.yml

version: '3.1'

services:
  react-app:
    container_name: react-app
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - ./dist:/usr/src/app/dist
    mem_limit: 2g

Now let’s create the Dockerfile

# Use a Node.js image as a base
FROM node:19-bullseye

WORKDIR /usr/src/app
COPY . .

# Install dependencies, build the application
RUN npm install 

EXPOSE 3000

# CMD to start the React application in development mode
CMD ["npm", "run", "dev"]

Remember that your application code has to be in the same directory as the Dockerfile.

To run it, we just have to type:

docker compose up -d

And once the container is running, we write this command that will generate the compiled production version in the /dist directory:

docker exec react-app npm run build

And we’ll have our Dist folder ready with the compiled React web.

To delete the container and the environment, once compiled, we will do:

docker compose -f docker-compose-build.yml down --rmi all

Leave a Comment