- Published
Adding Dockerfile to React application ⚛️🐬
- Authors
- Name
- Elif Nur Karakoç
In this article, I am explaining how to add a simple Dockerfile to React App. You can create a new React app with create-react-app. I will use my project that I created earlier
Docker can build images automatically by reading the instructions from a Dockerfile.
Dockerfile Example:
FROM node:19-slim
WORKDIR /src
COPY . .
RUN npm install --force
RUN npm install -g live-server
RUN npm run build
EXPOSE 8080
CMD ["live-server","build/"]
- With FROM, the 19-slim version of the node is set as the base image.
- WORKDIR tells the directory to work with.
- Everything in the src folder is transferred with COPY.
- After the necessary dependencies are downloaded with RUN, the build of the application is taken.
- With EXPOSE, the port that this image uses when it is a container is told.
- With CMD, the command to run the project is said.
After creating the Dockerfile file, the build command creates the container.
docker build . -t react-app
Let's run the created container with the run command:
docker run -p 9000:8080 react-app
- It opens out with the 9000 port.
We can access the application at http://127.0.0.1:9000/ .
Adding Docker Compose
Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration.
docker-compose.yml example:
version: "3.4"
services:
react-app:
container_name: react-app
build: .
ports:
- 9000:8080
- It may behave differently depending on the versions.
- Definitions are made for individual images under services.
- It is called build with the build under react-app and the Dockerfile in the directory it is in.
- Container_name defines the container name.
- Multiple ports can be defined with ports. In this definition, it works over 9000, but it takes port 8080 on the docker host.
To run the docker-compose file (gets the build and runs it):
docker-compose up
To get only build:
docker-compose build
To close and delete the container:
docker-compose down
Thank you for reading 💐
Elif