Location>code7788 >text

Net 6.0 Web API projects are mirrored and uploaded to a private repository, Harbor.

Popularity:468 ℃/2024-08-02 17:37:48

X. Preamble

This article begins with a brief introduction to Dockerfile contents and common commands;

Then there is the installation and configuration of Docker desktop in Windows environment;

Finally, the Web API example project was created and the steps from build to push to the Harbor mirror repository were briefly explained.

I. About Dockerfile

1.1 Dockerfile File Examples

#See /customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM /dotnet/aspnet:6.0 AS base
WORKDIR /app

# EXPOSE 811
# EXPOSE 443
# EXPOSE can be commented out,as an environment variable ASPNETCORE_URLS Configuration shall prevail
ENV ASPNETCORE_URLS=http://+:811

FROM /dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["Test.WebApplication1.ImgTest6.", "."]
RUN dotnet restore "./Test.WebApplication1.ImgTest6."
COPY . .
WORKDIR "/src/."
RUN dotnet build "Test.WebApplication1.ImgTest6." -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Test.WebApplication1.ImgTest6." -c Release -o /app/publish /p:UseAppHost=false

# Set time to Shanghai, China
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

# Setting up the environment as a development environment
ENV ASPNETCORE_ENVIRONMENT=Development

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Test.WebApplication1.ImgTest6."]

1.2 Common commands

1.2.1 FROM Specify base mirror or create new mirror stage

// Format
FROM <image># Defaults to the latest version if there is no tag or digest.
FROM <image>:<tag># tag labeling
FROM <image>:<digest># digest digest (usually a SHA256 hash)
// For example
FROM nginx
FROM /dotnet/sdk:6.0 AS build
FROM ubuntu:18.04@sha256:3c7f9d4a8b1f3e4e8b1f3e4e8b1f3e4e8b1f3e4e8b1f3e4e8b1f3e4e8b1f3e4

The first line of command in a Dockerfile file must be the FROM command. This can be reused when multiple incoming and outgoing images are needed at the same time.

FROM has another use, creating a copy of a mirror that identifies a mirror stage.

For example, the second line of the command in the following example:

# [Build phase]
# Build the project using the dotnet build command, the purpose of this phase is to compile the source code ready for release
RUN dotnet build "Test.WebApplication1.ImgTest6." -c Release -o /app/build
# [Preparing for release]
# The "publish" stage is created with this command. This stage inherits the compiled code from the "build" stage and prepares it for release.
FROM build AS publish
# The publish stage
# Publish the application to the /app/publish directory using the dotnet publish command.
# Publishing operations include optimizing the application to reduce its size, generating runtime dependencies, etc.
RUN dotnet publish "Test.WebApplication1.ImgTest6." -c Release -o /app/publish /p:UseAppHost=false

1.2.2 WORKDIR Setting the working directory

Similar to the cd command on the command line, subsequent commands are equivalent to running in the working directory.

# Format
WORKDIR /usr/workdir
# Example
WORKDIR /a # (this is the working directory: /a)
WORKDIR b # (This is the working directory: /a/b)
WORKDIR /c # (This is the working directory: /c)

1.2.3 EXPOSE Specifies the port on which to interact with the outside world.

# Format
EXPOSE 80
EXPOSE 443

This command simply declares what port the container intends to use; it does not actually change the container's network settings.

It is also possible to specify the exposed port without configuring the EXPOSE parameter. you can specify the container port by configuring an environment variable. for example:ENV ASPNETCORE_URLS=http://+:81

1.2.4 ENV Setting Environment Variables

This command is very simple, it's just for setting environment variables. Both the next commands and the program running in the container can use the environment variables defined here.

# Format
ENV <key>=<value>
# Example, this environment variable is usually used to specify the URL that the application listens on
ENV ASPNETCORE_URLS=http://+:81
# Indicates that the application will accept connection requests from any IP address (indicated by a +) and communicate using port 81

1.2.5 COPY Copying files

This command copies files from the current host, and also copies compiled files from the current folder to the current image.

# The first parameter refers to the source file path, [...]. indicates the current folder
# The second parameter refers to the destination path, [...]. means copy all the files in the current folder of the host computer.
COPY . .
# Use [--from=publish] to copy files from the publish mirror, where publish is the alias specified when introducing the mirror.
# Here, publish is the alias you specified when you imported the image.
# The last [. is the directory where you want to copy files to the current mirror. is the current path, and is usually used in conjunction with WORKDIR.
COPY --from=publish /app/publish .

1.2.6 RUN to build an image

Commands for installing other software or compiling files when building an image can be executed with the RUN command.

# Format
RUN <command> # shell execution
RUN ["executable", "param1", "param2"] # exec execution

Multiple commands can be connected with &&, to publish a Core project, for example, after copying the code to the image, you need to restore, build, and publish, so you can use it here, for example:

RUN dotnet restore "./Test.WebApplication1.ImgTest6." && dotnet build "./Test.WebApplication1.ImgTest6." -c Release -o /app/build && dotnet publish "./Test.WebApplication1.ImgTest6." -c Release -o /app/publish /p:UseAppHost=false

1.2.7 ENTRYPOINT container startup command

Specify the commands to be run when the container is started; you can append commands

# Format
ENTRYPOINT ["executable", "param1", "param2"]
ENTRYPOINT command param1 param2 # shell internal command
# Example
ENTRYPOINT ["dotnet", "Test.WebApplication1.ImgTest6."]
# Equivalent to executing the command dotnet Test.WebApplication1.ImgTest6. at the command line.

Note: Only one ENTRYPOINT command is allowed; specifying more than one overrides the previous setting, while theOnly the last ENTRYPOINT instruction is executed.

1.2.8 VOLUME Specifying the persistence directory

Used to create a data volume (volume) that allows a directory or file within a container to be shared with the host, the volume persists until no container is using it.

By using data volumes, data can be shared between containers or retained when containers are restarted. Changes to the volume take effect immediately, but do not affect the image.

# Format
VOLUME ["/path/to/dir"]
# Example
VOLUME ["/data"] # creates a data volume named /data
VOLUME ["/var/www", "/var/log/apache2"] # Creates two data volumes simultaneously

Note: The VOLUME command only declares the location of the data volumes, it does not actually create them. Data volumes are created while the container is running, usually through tools such as the docker run command or Docker Compose.

Reference:/WuLex/article/details/113730475    /guojiaqi_/article/details/135909376

Second, build the image and push it to the Harbor

2.1 Docker Installation

2.1.1 Environmental preparation

  • Enabling Related Windows Features

Open the Control Panel, go to Programs and Features, and check Hyper-V and Windows Subsystems for Linux. Windows Subsystem for Linux":

After the installation is complete, a reboot is required as prompted.

  • Install wsl

WSL (Windows Subsystem for Linux) is a subsystem of Windows 10 that allows users to run Linux distributions on Windows.

With WSL, users can install and run Linux command-line tools, applications and environments on Windows without the need for a traditional virtual machine or dual-boot setup.

wsl --install

Check if the installation was successful

Run it as shown belowwsl --list --verboseor simplified towsl -l -vThis is a list of all installed WSL distributions and their version numbers, as well as how to enter the wsl command mode:

Also, how do I make WSL and Windows file systems accessible to each other?

In the WSL, you can pass the/mnt/directory to access the Windows file system. For example, to access a file on the C drive in WSL, you can use the following path:

/mnt/c/path/to/your/

In Windows, you can get the\\wsl$\path to access the WSL file system. For example, to access a file in WSL in Windows, use the following path:

\\wsl$\your_linux_distro\home\your_username\path\to\your\

2.1.2 Problems encountered in environmental preparation

(1/3) During the installation of wsl, the following error occurs, the output is all ????? The error message is not clear

C:\WINDOWS\system32>wsl --install
Installation in progress: Ubuntu
installed Ubuntu。
Starting up. Ubuntu...
Installing, this may take a few minutes...
WslRegisterDistribution failed with error: 0x80370114
Error: 0x80370114 ??????????????????
Press any key to continue...
circulate“Ubuntu”The installation process fails,exit code: 1。
Error code: Wsl/InstallDistro/WSL_E_INSTALL_PROCESS_FAILED

The solution steps are as follows:

Search for "Apps and Browser Controls" in the win10 search box and go to the interface.
Click "Exploit Protection Settings".
Switch to "Program Settings"
Scroll down and find "C:\WINDOWS\System32\", click Edit.
Find "Control Flow Guard (CFG)" and cancel the "Alternative System Settings" below.
Open windows command line and type "net start vmcompute".

Reference:/gyjjj12/article/details/115531298

(2/3) The last part of the above restarts vmcompute with system error 1058.

C:\WINDOWS\system32>net start vmcompute
System error 1058 has occurred.
The service could not be started, either because it has been disabled or because the device associated with it is not started.

Solution:

  Service [Hyper-V Host Computing Service] is disabled or not running, enable it.

(3/3) Check if Hyper-V related services are enabled.

2.1.3 Download and installation

Download Docker Desktop from the official website:/products/docker-desktop/

Double-click to download the installation package (Docker Desktop ) to install, as shown below, the first item is recommended to check:

Then click the OK button to complete the installation.

Also, about WSL 2 and Hyper-V:

WSL 2 has a lower resource footprint than Hyper-V;
WSL 2 allows users to run containers without starting a full virtual machine, which simplifies operations and reduces system complexity;
For use cases where only Docker containers need to be run, WSL 2 provides adequate and optimized support;
You may need to rely on Hyper-V if you need to use other virtual machines or if you need fine-grained control over Docker resource allocation;
Docker images and containers cannot be shared between different Windows user accounts when using WSL 2 as a backend.

Verify that the installation was successful

Open or run Docker Desktop directly as administrator.

Docker is running after startup, as shown below:

The following is a simple procedure to test if Docker is installed successfully:

# View Version
C:\WINDOWS\system32>docker -v
Docker version 27.1.1, build 6312585
# Trying to pull a test image hello-world
C:\WINDOWS\system32>docker pull hello-world
Using default tag: latest
latest: Pulling from library/hello-world
c1ec31eb5944: Pull complete
Digest: sha256:1408fec50309afee38f3535383f5b09419e6dc0925bc69891e79d84cc4cdcec6
Status: Downloaded newer image for hello-world:latest
/library/hello-world:latest
...
# Run the test image hello-world,successful output:Hello from Docker!
C:\WINDOWS\system32>docker run hello-world

Hello from Docker!
This message shows that your installation appears to be working correctly.
# View all current mirrors
C:\WINDOWS\system32>docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest d2c94e258dcb 15 months ago 13.3kB

2.1.4 Necessary Docker Configuration

  • Domestic Mirror Repository Configuration

In the configuration of Docker-->Setting-->Docker Engine module, add a new configuration item "registry-mirrors": (recommended to use the mirror address of the AliCloud, there is a detailed explanation of how to get later)

{
	"builder": {
		"gc": {
			"defaultKeepStorage": "20GB",
			"enabled": true
		}
	},
	"experimental": false,
	"registry-mirrors": [
		".",
		""
	]
}

Among them, "." is the mirror address of NetEase Cloud; "" is the mirror address of University of Science and Technology of China.

Finally, clicking "apply & restart" will automatically restart Docker to make the new configuration take effect. You can also restart Docker with the commanddocker infoto see all current configuration items.

Recommended to use personal AliCloud mirror address, need to apply separately, method: login address [], and then operate as follows, you need to apply for it if you haven't applied for it before:

  

For specific configurations, you can refer to the operating documentation of the corresponding system to update the configuration.

2.2 Creating a Web API Project

Create a new project in the editor and check the configuration as shown below:

After the project is created, a Dockerfile file is automatically generated, which needs to be modified accordingly, as described in this article.1.1 Dockerfile File Examples

The following is a sample file directory:

2.3 Mirror Compilation and Push to Harbor Mirror Repository

First, in the project folder, open the command line tool, Shift+Right mouse button, select "Open Powershell window here", after opening, type cmd to enter command line mode.

Step 1: Mirror build

Build the project with the build statement:

docker build -t test-dotnet/testwebapplication1imgtest60:stage_v1.0 .

where test-dotnet denotes the project name, test-dotnet/testwebapplication1imgtest60 denotes the image name, and stage_v1.0 after the colon is the label given to the image.

Step 2: Labeling

Match the local mirror to the mirror in the private Harbor repository: (this is the domain name of the repository, you need to change it to your own)

docker tag test-dotnet/testwebapplication1imgtest60:stage_v1.0 /test-dotnet/testwebapplication1imgtest60:stage_v1.0

Subsequent step: push the local image to the remote repository

// Log in first
docker login
// Once you're logged in, push
docker push /test-dotnet/testwebapplication1imgtest60:stage_v1.0

Finally, log in to Harbor for the repository to see if the image with the corresponding tag has been uploaded successfully.

After confirming a successful push, the interface pulls through the mirror address. Example:

// Domain name + project name + Tag to pull the specified version
docker pull /test-dotnet/testwebapplication1imgtest60:stage_v1.0

2.4 Problems encountered during mirror building and pushing

2.4.1 Program does not contain a static 'Main' method suitable for an entry point

Solution: The solution file (.sln) needs to be in the same directory as the project files (.csproj, Dockerfile).

Based on the prompt, it is confirmed that the cause of the problem cannot be determined, and the Main method is not actually included in the project.

Details are available:/questions/52991469/getting-program-does-not-contain-a-static-main-method-suitable-for-an-entry-p

2.4.2 Error prompts caused by Docker running abnormally

ERROR: request returned Internal Server Error for API route and version http://%2F%2F.%2Fpipe%2FdockerDesktopLinuxEngine/_ping, check if the server supports the requested API version

Just restart Docker Desktop.