Day 2/40
How to Dockerize a Project
GitHub link - https://github.com/SUBHAM-NANDI/40DaysKubernetes/tree/main/Day%202
Install Docker Desktop
To get started with Docker on your local machine, download the Docker Desktop client:
Getting Started with Docker
- Clone a Sample Repository: You can either use your own project or clone a sample repository using the following command:
git clone https://github.com/docker/getting-started-app.git
- Navigate to the Project Directory: Change your working directory to the project folder:
cd getting-started-app/
-
Create a Dockerfile:
Inside the project directory, create a new file named
Dockerfile
:
touch Dockerfile
-
Add Dockerfile Content:
Open the
Dockerfile
in your preferred text editor and paste the following content:
FROM node:18-alpine
WORKDIR /app
COPY . .
RUN yarn install --production
CMD ["node", "src/index.js"]
EXPOSE 3000
This Dockerfile sets up a Node.js environment, installs dependencies, and specifies how to run the application.
- Build the Docker Image: Build the Docker image from the Dockerfile using the following command:
docker build -t day02-todo .
- Verify the Docker Image: After building, check that the image was created and stored locally:
docker images
Pushing the Docker Image to Docker Hub
- Log In to Docker Hub: Authenticate with Docker Hub to push your image:
docker login
- Tag the Image: Tag your image to prepare it for pushing to a remote repository:
docker tag day02-todo:latest username/new-reponame:tagname
- Push the Image: Push the tagged image to Docker Hub:
docker push username/new-reponame:tagname
Pulling and Running the Docker Image
- Pull the Image in Another Environment: If you need to pull the image to a different environment, use:
docker pull username/new-reponame:tagname
- Run the Docker Container: Start the container and map the application to port 3000:
docker run -dp 3000:3000 --name docker-container-name username/new-reponame:tagname
After this, your app should be accessible at http://localhost:3000
.
Additional Docker Commands
- Access the Container Shell: To enter the running container, use:
docker exec -it containername sh
or
docker exec -it containerid sh
- View Container Logs: To check the logs from your container:
docker logs containername
or
docker logs containerid