» Make Web Chat App Front-End with React » 2. Development » 2.9 Dockerfile

Dockerfile

Docker allows developers to package their applications along with all dependencies into a single unit called a container.

Read env vars

@@ -26,6 +26,8 @@ const SOUNDS = {
   ding: process.env.PUBLIC_URL + "/ding.mp3",
 };
 
+const CHAT_SERVER_URL = process.env.CHAT_SERVER_URL || "http://localhost:4000";
+
 function dingIt() {
   const sound = new Howl({
     src: [SOUNDS.ding],
@@ -52,7 +54,7 @@ function App() {
 
   useEffect(() => {
     if (!user.name) return;
-    const socket = io("http://localhost:4000");
+    const socket = io(CHAT_SERVER_URL);
     socket.on("error", (error) => {
       console.error("Socket error:", error);
     });

Dockerfile for the service

Add Dockerfile:

# Use the official Node.js image with specified version
FROM node:20.11-alpine3.18

# Set the working directory inside the container
WORKDIR /usr/src/app

# Copy package.json and package-lock.json to the working directory
COPY package*.json ./

# Install project dependencies
RUN npm install
RUN npm install -g serve

# Copy the rest of the application code to the working directory
COPY src/ /usr/src/app/src
COPY public/ /usr/src/app/public

# Build
RUN npm run build

# Command to run the application
CMD ["serve", "-s", "build", "-p", "3000"]

You can use serve or nginx or any other static servers to serve files.

With this Dockerfile, you can build the front-end app as a docker image. Later you may choose to deploy it with Docker Compose or K8s.

PrevNext