Dockerfile
Docker 允许开发人员将他们的应用程序以及所有依赖项打包成一个称为容器的单个单元。这确保了在不同环境(如开发、测试和生产)之间的一致性,减少了“但是它在我的机器上运行正常”的问题。
读取环境变量
@@ -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 文件
添加 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"]
有了这个 Dockerfile,你可以将这个前端 app 构建成一个 docker image。之后你就可以用 Docker Compose 或 Kubernetes 部署它。