-
Create a directory for the express project
mkdir project
-
Go to the directory
cd project
-
Initialize a Node JS project. Answer all the question prompted on the terminal. Finally a
package.json
file will be created in theproject/
directorynpm init
-
Install
express
npm install express
-
Create a file for writing the express web app.
vi app.js
-
Write the code in
app.js
as belowconst express = require("express"); const app = express(); app.get("/", (req, res) => { res.send({ data: "HELLO WORLD" }); }); app.listen(5000, () => { console.log("START SERVER AT PORT 5000"); });
-
Create and write a
Dockerfile
as belowFROM node:18-alpine # create "app" directory in the docker image RUN mkdir app # set "app" directory as the root working directory WORKDIR app # copy some files from the local machine into "app" directory in docker image COPY app.js . COPY package*.json . # install dependencies at build stage RUN npm install # tell the develooper if this container will be run at port 5000/TCP EXPOSE 5000 # run the program (web app) when the container is running CMD node ./app.js
-
Build the image. Let say you are currently opening
root
directory where theproject
directory is locatedroot
is the parent directory ofproject
)docker build -t ricoputra/project-express project
-
Create a container from the image and set the PORT as well
docker container create --name ricoputra_project-express -p 5000:5000 ricoputra/project-express
-
Start/run the container
docker container start ricoputra_project-express
-
Open the web app on the browser by entering this url:
localhost:5000/
and you will see the response below:{ "data": "HELLO WORLD" }