Dockerizing a React web application
Creating a React application and dockerizing it to get the application up and running with just one command.
Prerequisites:
1. Create a React Application
In the terminal, cd into the folder you want your project in and use one of the following commands to create a React web application.
# using npx
npx create-react-app my-new-app
# using npm
npm init react-app my-new-app
# using yarn
yarn create react-app my-new-app
To start your application from terminal:
# with npm
npm run start
# with yarn
yarn start
Note: We won’t need this step because Docker will do it for us.
2. Dockerize the application
Initial folder structure of the application:
my-app
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ └── manifest.json
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
└── serviceWorker.js
├── README.md
├── node_modules
├── package.json
├── .gitignore
Add a new file at the root of the project and name it Dockerfile.
Add this code to the Dockerfile:
FROM node:alpine
WORKDIR /app
COPY package.json /app
RUN yarn install
COPY . /app
CMD ["yarn", "run", "start"]
3. Add Docker Compose
Create another file at the root of the project and name it docker-compose.yml.
version: "3"
services:
client:
stdin_open: true
build:
context: .
dockerfile: Dockerfile
ports:
- "3000:3000"
volumes:
- "/app/node_modules"
- "./:/app"
Add another file called .dockerignore at the root of the project and this code:
node_modules
build
.dockerignore
Dockerfile
Structure after adding Dockerfile, docker-compose.yml and .dockerignore files:
my-app
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ └── manifest.json
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
└── serviceWorker.js
├── README.md
├── node_modules
├── .gitignore
├── .dockerignore
├── Dockerfile
├── docker-compose.yml
├── package.json
4. Run the application!
Now, the final and only command to get your project up and running:
docker-compose up
Note: You have to cd into the project folder in your terminal and then run this command.
Now your application is running at http://localhost:3000.
For anyone who is wondering, hot reload works this way too.
The repository for this project lives at: https://github.com/shrued/react-docker.