Deploy Socket.IO, Express, Vue, Node.js using Docker
I am making a web application and planning to deploy it to AWS EC2 Instance using Docker (ECR -> ECS -> EC2).
In localhost, my Vue front-end is running on port 5173 and my back-end is running on port 5000.
This is how my app.ts
in back end looks like:
import dotenv from 'dotenv';
dotenv.config();
import express from 'express';
import { createServer } from 'http';
import cors from 'cors';
import { Server } from 'socket.io';
import cookieParser from 'cookie-parser';
import path from 'path';
const app = express();
app.use(cors());
app.use(cookieParser());
const uri = process.env.MONGODB_URI!;
const port = process.env.PORT!;
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../public/index.html'));
});
const server = createServer(app);
const io = new Server(server, {
cors: {
origin: 'http://localhost:5173',
methods: ['GET', 'POST'],
credentials: true,
},
});
server.listen(port, () => {
console.log(`Socket.io server is running on port ${port}`);
});
I have a socket.ts
file beside the main.ts
file in the front end which is used to connect the socket to the backend.
import { io } from 'socket.io-client';
const socket = io('http://localhost:5000');
export { socket };
I have set up the Dockerfile
like this:
FROM node:latest as server
WORKDIR /srv/app
COPY ./server/package*.json ./
RUN npm install
COPY ./server .
RUN npm run build
FROM node:latest as client
WORKDIR /srv/app
COPY ./client/package*.json ./
RUN npm install
COPY ./client .
RUN npm run build
FROM node:latest as production
WORKDIR /srv/app
RUN mkdir /public
COPY --from=server /srv/app/dist ./
COPY --from=client /srv/app/dist ./public
ENV NODE_ENV=production
EXPOSE 5000
CMD ["node", "app.js"]
and compose.yml
file:
services:
app:
container_name: app
build: .
env_file:
- ./prod.env
ports:
- "5000:5000"
expose:
- 5000
How should I modify to get the socket.io working when deploy the docker image to AWS EC2 Instance?