Containers are the building blocks of docker. Here's the note will go through various commands that will help manipulate and create containers, to give better understanding of how docker works.
First, create 3 files: Dockerfile, package.json, server.js
Dockerfile:
FROM node:17-slim
WORKDIR /app
COPY . .
RUN npm install
CMD ["node", "server.js"]
EXPOSE 3000
package.json:
{
"name": "yay-docker",
"dependencies": {
"express": "^4.17.1"
}
}
server.js:
const server = require("express")();
server.listen(8080, async () => { });
server.get("/nodejs", async (_, response) => {
console.log('Request Received for nodejs');
response.json({ "yay": "docker" });
});
Create an image and name it "simple_nodejs" from current folder. It will start multiple layers for downloading the node:17-slim image. Once done it will run npm install to install dependencies like express from your package.json file.
docker build -t simple_nodejs .
Run the image as container named "simple_nodejs" at port 3000 (external) while the node app running at port 8080 (internal).
docker run -p 3000:8080 -d simple_nodejs
Now, we can test the container by browsing to http://localhost:3000/
List running containers
docker ps -a
Prints container logs
docker logs <container-id>
Access the container
docker exec -it <container-id> /bin/sh
Start, stop, and remove container:
docker start <container-id>
docker stop <container-id>
docker rm <container-id>
Links: