Docker is a platform that allows you to package applications and their dependencies into lightweight containers. Containers are portable and ensure your application runs the same way in development, testing, and production environments.
Docker simplifies deployment by encapsulating the application and its environment in a single container. It is ideal for microservices and cloud-based applications.
Follow these steps:
// Download and install Docker Desktop for your OS:
// https://www.docker.com/products/docker-desktop
Ensure Docker is running before proceeding.
// Create a Dockerfile in the root of your project:
FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
WORKDIR /src
COPY . .
RUN dotnet restore
RUN dotnet publish -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "MyApp.dll"]
The Dockerfile describes how to build and run the application in a container.
// Open a terminal in the project directory and run:
docker build -t myapp:latest .
This creates a Docker image named myapp
.
// Start a container from the image:
docker run -d -p 8080:80 --name myapp-container myapp:latest
Access your application at http://localhost:8080
.
// Log in to Docker Hub:
docker login
// Tag the image:
docker tag myapp:latest yourdockerhubusername/myapp:latest
// Push the image:
docker push yourdockerhubusername/myapp:latest
This uploads the image to Docker Hub for deployment.
// Pull the image on the target server:
docker pull yourdockerhubusername/myapp:latest
// Run the container:
docker run -d -p 8080:80 --name myapp-container yourdockerhubusername/myapp:latest
// View running containers:
docker ps
// Stop a container:
docker stop myapp-container
// Remove a container:
docker rm myapp-container
Use Docker commands to manage your containerized application.