使用docker部署.net core应用

CentOS

  使用VS2017新建一个asp.net core项目

发布web应用程序

使用FTP工具,将程序文件copy到linux上

XShell连上linux并登陆

cd /CoreWebDemo #进入应用程序目录

vi Dockerfile #编辑Docker配置文件,文件不存在会自动创建

#基于microsoft/aspnetcore或者microsoft/dotnet:runtime来构建我们的镜像
FROM microsoft/dotnet:runtime

#拷贝项目publish文件夹中的所有文件到 docker容器中的publish文件夹中  
COPY . /publish

#设置工作目录为 `/publish` 文件夹,即容器启动默认的文件夹
WORKDIR /publish

#设置Docker容器对外暴露80端口
EXPOSE 80

#使用CoreWebDemo.dll来运行应用程序

ENTRYPOINT ["dotnet", "CoreWebDemo.dll"]
View Code

可以选择runtime或者完整sdk来创建镜像,完整的sdk创建的镜像有1.75G左右,而runtime创建的镜像只有300M左右,建议使用runtime来创建镜像。

 

编辑完毕后,保存退出

vi /etc/docker/daemon.json #编辑配置文件使用加速服务,如果不存在自动新增
{
  "registry-mirrors": [
    "https://registry.docker-cn.com"
  ]
}
View Code

编辑完成,保存退出

$ sudo systemctl daemon-reload
$ sudo systemctl restart docker #重启docker

docker build -t 镜像名称 .  #建立一个镜像(注意最后一个空格+点),该过程可能会非常缓慢,建议使用加速器或者VPN

 

docker run --name 容器名称 -d -p 80:80 -e "ASPNETCORE_URLS=http://+:80" 镜像名称

-d 后台进程。

-p是进行宿主和容器之间端口的映射,(-p 宿主端口:容器端口)

ASPNETCORE_URLS=http://+:80 应用程序启动时绑定80端口

如果防火墙没有开启80端口,就重新开启

firewall-cmd --zone=public --add-port=80/tcp --permanent 
systemctl stop firewalld.service             #停止firewall
systemctl disable firewalld.service        #禁止firewall开机启动

--zone #作用域
--add-port=80/tcp #添加端口,格式为:端口/通讯协议
--permanent #永久生效,没有此参数重启后失效

 docker添加加速服务教程: https://yeasy.gitbooks.io/docker_practice/content/install/centos.html

PS:如果使用runtime来创建镜像,可能会出现错误

error:
An assembly specified in the application dependencies manifest (CoreWebDemo.deps.json) was not found:
package: 'Microsoft.ApplicationInsights.AspNetCore', version: '2.1.1'
path: 'lib/netstandard1.6/Microsoft.ApplicationInsights.AspNetCore.dll'
This assembly was expected to be in the local runtime store as the application was published using the following target manifest files:
aspnetcore-store-2.0.0-linux-x64.xml;aspnetcore-store-2.0.0-osx-x64.xml;aspnetcore-store-2.0.0-win7-x64.xml;aspnetcore-store-2.0.0-win7-x86.xml

编辑web项目的csproj文件

增加如一行到 csjproj文件中即可:<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest> 
最后csjproj文件看上去像这个样子:

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
  </PropertyGroup>

重新发布,上传到linux。执行docker run语句,就会创建成功。

docker常用命令

删除镜像

docker rmi c861a419888a(镜像ID)

删除容器

docker rm xxxxxxxxx(容器id)

创建容器

 docker commit -p xxxxxxxxxxx(容器id) name(快照名称)

保存本地tar备份

 docker save -o /xxxxxxxx.tar name(镜像名称)

还原本地tar备份

docker load -i /xxxxx.tar 

查看所有容器

docker ps -a

停止一个容器

docker stop 容器名称

 

posted @ 2018-01-20 18:21  Twinhead  阅读(447)  评论(0编辑  收藏  举报