Docker
🐳

Docker

Tag
Last Edited Time
Dec 20, 2021 08:43 PM
Created
Jan 4, 2021 03:08 PM

Note

🐳Docker狂神笔记

Reference

30 分钟快速入门 Docker 教程
原文地址: 梁桂钊的博客 博客地址: blog.720ui.com 欢迎关注公众号:「服务端思维」。一群同频者,一起成长,一起精进,打破认知的局限性。 在没有 Docker 的时代,我们会使用硬件虚拟化(虚拟机)以提供隔离。这里,虚拟机通过在操作系统上建立了一个中间虚拟软件层 Hypervisor ,并利用物理机器的资源虚拟出多个虚拟硬件环境来共享宿主机的资源,其中的应用运行在虚拟机内核上。但是,虚拟机对硬件的利用率存在瓶颈,因为虚拟机很难根据当前业务量动态调整其占用的硬件资源,因此容器化技术得以流行。其中,Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上。 Docker 容器不使用硬件虚拟化,它的守护进程是宿主机上的一个进程,换句话说,应用直接运行在宿主机内核上。因为容器中运行的程序和计算机的操作系统之间没有额外的中间层,没有资源被冗余软件的运行或虚拟硬件的模拟而浪费掉。 Docker 的优势不仅如此,我们来比较一番。 Docker 由镜像(Image)、容器(Container)、仓库(Repository) 三部分组成。 Docker 的镜像可以简单的类比为电脑装系统用的系统盘,包括操作系统,以及必要的软件。例如,一个镜像可以包含一个完整的 centos 操作系统环境,并安装了 Nginx 和 Tomcat 服务器。注意的是,镜像是只读的。这一点也很好理解,就像我们刻录的系统盘其实也是可读的。我们可以使用 docker images 来查看本地镜像列表。 Docker 的容器可以简单理解为提供了系统硬件环境,它是真正跑项目程序、消耗机器资源、提供服务的东西。例如,我们可以暂时把容器看作一个 Linux 的电脑,它可以直接运行。那么,容器是基于镜像启动的,并且每个容器都是相互隔离的。注意的是,容器在启动的时候基于镜像创建一层可写层作为最上层。我们可以使用 docker ps -a 查看本地运行过的容器。 Docker 的仓库用于存放镜像。这一点,和 Git 非常类似。我们可以从中心仓库下载镜像,也可以从自建仓库下载。同时,我们可以把制作好的镜像 commit 到本地,然后 push 到远程仓库。仓库分为公开仓库和私有仓库,最大的公开仓库是官方仓库 Dock Hub,国内的公开仓库也有很多选择,例如阿里云等。 笔者认为,Docker 对开发流程的影响在于使环境标准化。例如,原来我们存在三个环境:开发(日常)环境、测试环境、生产环境。这里,我们对于每个环境都需要部署相同的软件、脚本和运行程序,如图所示。事实上,对于启动脚本内容都是一致的,但是没有统一维护,经常会出问题。此外,对于运行程序而言,如果所依赖的底层运行环境不一致,也会造成困扰和异常。 现在,我们通过引入 Docker 之后,我们只需要维护一个 Docker 镜像。换句话说,多套环境,一个镜像,实现系统级别的一次构建到处运行。此时,我们把运行脚本标准化了,把底层软件镜像化了,然后对于相同的将要部署的程序实行标准化部署。因此,Docker 为我们提供了一个标准化的运维模式,并固化运维步骤和流程。 通过这个流程的改进,我们更容易实现 DevOps 的目标,因为我们的镜像生成后可以跑在任何系统,并快速部署。此外,使用 Docker 的很大动力是基于 Docker 实现弹性调度,以更充分地利用机器资源,节省成本。 哈哈,笔者在使用 Docker 过程中,还发现了一些很棒的收益点,例如我们发布回滚的时候只需要切换 TAG 并重启即可。还比如,我们对环境升级,也只需要升级基础镜像,那么新构建的应用镜像,自动会引用新的版本。(欢迎补充~~~) 现在,我们需要安装以下步骤安装 Docker。 官方下载地址:(Mac): download.docker.com/mac/stable/...
2020年最完整的Docker v19.x入门教程
引言 非常感谢你能在闲暇之余点开了小编的文章,这篇文章是2020年较为全面的Docker19入门的一个教程,不过他更像一个Docker的手册,所以需要你来花费较长的时间来阅读,你可以【收藏】或者【点赞】来记录这篇文章到【你的喜欢】里,这样方便你以后查阅这篇文章。有什么问题可以评论留言,小编会在看到的第一时间给你回复,方便的话点个【关注】鼓励一下小编,小编还会继续创作更多的有关IT方面的文章,谢谢。 环境 简单来说就是将应用程序部署到独立的容器,每个容器相当于一个小的linux系统。通过将容器进行打包成镜像,放到将镜像放到任何有Docker环境的系统上运行。 使用Go语言开发,基于Apache2.0开源协议。 Docker提供简单的轻量的服务器部署。 可以清楚的将开发人员与运维人员的职责分离。 快速的开发生命周期。 面向服务的架构,每个服务相互隔离。 可以使用Docker容器开发后测试然后部署服务。 创建相互隔离的运行环境。 搭建测试环境,例如集群测试。 Docker Client 客户端 Docker Daemon 守护进程 Docker Image 镜像 Docker Container 容器 Docker Registry 仓库 Docker是C/S架构的程序,其中Docker Client扮演的是客户端,Docker Daemon扮演的是服务器端。 docker Client即可是在本机也可以在远程。 镜像好比容器的源代码,保存了容器启动的各种条件。 Docker将一些容器运行的系统与应用服务打包起来,通过联合加载的方式运行,这个打包起来的文件就成为镜像。 一个镜像可以放到另一个镜像的底部,最下面的镜像被称为基础镜像。 Docker的容器是Dacker的执行单元。 如果说镜像是打包,那么容器就是运行打包好的镜像。 Docker仓库是用来保存Docker镜像的地方,分为: $ docker version $ docker info $ docker search $ docker pull
2020年最完整的Docker v19.x入门教程

Code

Run a container

docker run -d -p 80:80 docker/getting-started
  • d - run the container in detached mode (in the background)
  • p 80:80 - map port 80 of the host to port 80 in the container
  • docker/getting-started - the image to use

Dockerfile

FROM node:12-alpine
WORKDIR /app
COPY . .
RUN yarn install --production
CMD ["node", "src/index.js"]

Build Container Image

# 
Finally, the -t flag tags our image. Think of this simply as a human-readable name for the final image. Since we named the image getting-started, we can refer to that image when we run a container.
The . at the end of the docker build command tells that Docker should look for the Dockerfile in the current directory.

Remove

Method 1

# Get ID
docker ps
# Swap out <the-container-id> with the ID from docker ps
docker stop <the-container-id>
# Remove
docker rm <the-container-id>

Method 2

Removing a container using the Docker Dashboard

Push

docker push jimschenchen/getting-started

Tag and push

  1. Login to the Docker Hub using the command docker login -u YOUR-USER-NAME.
  1. Use the docker tag command to give the getting-started image a new name. Be sure to swap out YOUR-USER-NAME with your Docker ID.
  1. Now try your push command again. If you're copying the value from Docker Hub, you can drop the tagname portion, as we didn't add a tag to the image name. If you don't specify a tag, Docker will use a tag called latest.
 
 
docker tag getting-started jimschenchen/getting-started
docker push jimschenchen/getting-started
 
docker run -dp 3000:3000 jimschenchen/getting-started

Test

 

EXEC

docker exec <container-id> cat /data.txt
 

Named Volume

Volumes provide the ability to connect specific filesystem paths of the container back to the host machine. If a directory in the container is mounted, changes in that directory are also seen on the host machine. If we mount that same directory across container restarts, we'd see the same files.
  1. Create a volume by using the docker volume create command.
    1. docker volume create todo-db
  1. Stop the todo app container once again in the Dashboard (or with docker rm -f <id>), as it is still running without using the persistent volume.
  1. Start the todo app container, but add the v flag to specify a volume mount. We will use the named volume and mount it to /etc/todos, which will capture all files created at the path.
    1. docker run -dp 3000:3000 -v todo-db:/etc/todos getting-started
todo-db:/etc/todos : todo-db Host volume /etc/todos dir in container
 
A lot of people frequently ask "Where is Docker actually storing my data when I use a named volume?" If you want to know, you can use the docker volume inspect command.
The Mountpoint is the actual location on the disk where the data is stored. Note that on most machines, you will need to have root access to access this directory from the host. But, that's where it is!
Docker数据存储之Volumes
默认容器的数据的读写发生在容器的存储层,当容器被删除时其上的数据将会丢失。所以我们应该尽量保证容器存储层不发生写操作,为了实现数据的持久化存储我们需要选择一种方案来保存数据,当前有以下几种方式: 下图展示了这三种技术: Volumes(数据卷)是一个可供一个或多个容器使用的位于宿主机上特殊目录,它拥有以下特性: 数据卷可以在容器间共享和重用 对数据卷的写入操作,不会对镜像有任何影响 数据卷默认会一直存在,即使容器被删除 使用数据卷的目的是持久化容器中的数据,以在容器间共享或者防止数据丢失(写入容器存储层的数据会丢失)。 使用数据卷的步骤一般分为两步: 创建一个数据卷 使用-v或--mount参数将数据卷挂载容器指定目录中,这样所有该容器针对该指定目录的写操作都会保存在宿主机上的Volume中。 创建一个Volume: $ docker volume create my-vol 查看Volumes: $ docker volume ls local my-vol $ docker volume inspect my-vol [ { "Driver": "local", "Labels": {}, "Mountpoint": "/var/lib/docker/volumes/my-vol/_data", "Name": "my-vol", "Options": {}, "Scope": "local" } ] 我么可以看到创建的Volume my-vol保存在目录/var/lib/docker/volumes/下,以后所有针对该Volume的写数据都会保存中目录/var/lib/docker/volumes/my-vol/_data 下。 删除一个Volume: $ docker
Docker数据存储之Volumes
notion image
 

Bind Mounts

Bind mounts模式和Volumes非常相似,不同点在于Bind mounts模式是将宿主机上的任意文件或文件夹挂载到容器,而Volumes本质上是将Docker服务管理的一块区域(默认是/var/lib/docker/volumes下的文件夹)挂载到容器。
With bind mounts, we control the exact mountpoint on the host. We can use this to persist data, but is often used to provide additional data into containers. When working on an application, we can use a bind mount to mount our source code into the container to let it see code changes, respond, and let us see the changes right away
Docker数据存储之Bind mounts
阅读本文前,希望你已经对Volumes有了初步的了解,具体可以参考这篇文章: 默认容器的数据的读写发生在容器的存储层,当容器被删除时其上的数据将会丢失。所以我们应该尽量保证容器存储层不发生写操作,为了实现数据的持久化存储我们需要选择一种方案来保存数据,当前有以下几种方式: 下图展示了这三种技术: Bind mounts模式和Volumes非常相似,不同点在于Bind mounts模式是将宿主机上的任意文件或文件夹挂载到容器,而Volumes本质上是将Docker服务管理的一块区域(默认是/var/lib/docker/volumes下的文件夹)挂载到容器。 Bind mounts的使用和Volumes类似,也是通过-v或--mount 参数将宿主机文件挂载容器中。下面是一个例子: 使用--mount参数时,需要指定 type=bind : $ docker run -d \ --name=nginxtest \ --mount type=bind,source=/usr/local/web,destination=/usr/share/nginx/html \ nginx:latest 上面的例子将宿主机上的/usr/local/web文件夹挂载到容器中的/usr/share/nginx/html文件夹。 $ docker run -d \ --name=nginxtest \ -v /usr/local/web:/usr/share/nginx/html \ nginx:latest 挂载成功后,容器从/usr/share/nginx/html目录下读取或写入数据,实际上都是从宿主机的 /usr/local/web目录中读取或写入数据。因此Volumes或Bind mounts也可以看作是容器和宿主机共享文件的一种方式。 如果你使用Bind mounts挂载宿主机目录到一个容器中的非空目录,那么此容器中的非空目录中的文件会被隐藏,容器访问这个目录时能够访问到的文件均来自于宿主机目录。 这也是Bind mounts模式和Volumes模式最大的行为上的不同。 请参考这篇文章: Docker数据存储总结
Docker数据存储之Bind mounts
docker run -dp 3000:3000 `
    -w /app -v "$(pwd):/app" `
    node:12-alpine `
    sh -c "yarn install && yarn run dev"
docker run -dp 3000:3000 \
    -w /app -v "$(pwd):/app" \
    node:12-alpine \
    sh -c "yarn install && yarn run dev"
 

Container Networking

If two containers are on the same network, they can talk to each other. If they aren't, they can't.
 

Starting MySQL

  1. Create the network.
    1. docker network create todo-app
  1. Start a MySQL container and attach it to the network. We're also going to define a few environment variables that the database will use to initialize the database (see the "Environment Variables" section in the MySQL Docker Hub listing).
    1. If you are using PowerShell then use this command.
      docker run -d ` --network todo-app --network-alias mysql ` -v todo-mysql-data:/var/lib/mysql ` -e MYSQL_ROOT_PASSWORD=secret ` -e MYSQL_DATABASE=todos ` mysql:5.7
      You'll also see we specified the --network-alias flag. We'll come back to that in just a moment.
      Pro-tip
      You'll notice we're using a volume named todo-mysql-data here and mounting it at /var/lib/mysql, which is where MySQL stores its data. However, we never ran a docker volume create command. Docker recognizes we want to use a named volume and creates one automatically for us.
  1. To confirm we have the database up and running, connect to the database and verify it connects.
    1. docker exec -it <mysql-container-id> mysql -p
      When the password prompt comes up, type in secret. In the MySQL shell, list the databases and verify you see the todos database.
      mysql> SHOW DATABASES;
      You should see output that looks like this:
      +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | | todos | +--------------------+ 5 rows in set (0.00 sec)
      Hooray! We have our todos database and it's ready for us to use!
       
       

      Connecting to MySQL

      Now that we know MySQL is up and running, let's use it! But, the question is... how? If we run another container on the same network, how do we find the container (remember each container has its own IP address)?
      To figure it out, we're going to make use of the nicolaka/netshoot container, which ships with a lot of tools that are useful for troubleshooting or debugging networking issues.
    2. Start a new container using the nicolaka/netshoot image. Make sure to connect it to the same network.
    3. Inside the container, we're going to use the dig command, which is a useful DNS tool. We're going to look up the IP address for the hostname mysql.
      1. And you'll get an output like this...
        ; <<>> DiG 9.14.1 <<>> mysql
        ;; global options: +cmd
        ;; Got answer:
        ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 32162
        ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
        
        ;; QUESTION SECTION:
        ;mysql.             IN  A
        
        ;; ANSWER SECTION:
        mysql.          600 IN  A   172.23.0.2
        jiushi
        ;; Query time: 0 msec
        ;; SERVER: 127.0.0.11#53(127.0.0.11)
        ;; WHEN: Tue Oct 01 23:47:24 UTC 2019
        ;; MSG SIZE  rcvd: 44
        In the "ANSWER SECTION", you will see an A record for mysql that resolves to 172.23.0.2 (your IP address will most likely have a different value). While mysql isn't normally a valid hostname, Docker was able to resolve it to the IP address of the container that had that network alias (remember the --network-alias flag we used earlier?).
        What this means is... our app only simply needs to connect to a host named mysql and it'll talk to the database! It doesn't get much simpler than that!
         
         
      2. We'll specify each of the environment variables above, as well as connect the container to our app network.
        1. If you are using PowerShell then use this command.
      3. If we look at the logs for the container (docker logs <container-id>), we should see a message indicating it's using the mysql database.
      4. Open the app in your browser and add a few items to your todo list.
      5. Connect to the mysql database and prove that the items are being written to the database. Remember, the password is secret.
        1. And in the mysql shell, run the following:
          Obviously, your table will look different because it has your items. But, you should see them stored there!
        If you take a quick look at the Docker Dashboard, you'll see that we have two app containers running. But, there's no real indication that they are grouped together in a single app. We'll see how to make that better shortly!
         
         
         

        Using Docker Compose

        Docker Compose is a tool that was developed to help define and share multi-container applications. With Compose, we can create a YAML file to define the services and with a single command, can spin everything up or tear it all down.
        The big advantage of using Compose is you can define your application stack in a file, keep it at the root of your project repo (it's now version controlled), and easily enable someone else to contribute to your project. Someone would only need to clone your repo and start the compose app. In fact, you might see quite a few projects on GitHub/GitLab doing exactly this now.
        So, how do we get started?
         

        Installing Docker Compose

        If you installed Docker Desktop/Toolbox for either Windows or Mac, you already have Docker Compose! Play-with-Docker instances already have Docker Compose installed as well. If you are on a Linux machine, you will need to install Docker Compose using the instructions here.
        After installation, you should be able to run the following and see version information.
        docker-compose version

        Creating our Compose File

      6. At the root of the app project, create a file named docker-compose.yml.
      7. In the compose file, we'll start off by defining the schema version. In most cases, it's best to use the latest supported version. You can look at the Compose file reference for the current schema versions and the compatibility matrix.
      8. Next, we'll define the list of services (or containers) we want to run as part of our application.
        And now, we'll start migrating a service at a time into the compose file.

        Defining the App Service

        To remember, this was the command we were using to define our app container.
        If you are using PowerShell then use this command.
      9. First, let's define the service entry and the image for the container. We can pick any name for the service. The name will automatically become a network alias, which will be useful when defining our MySQL service.
      10. Typically, you will see the command close to the image definition, although there is no requirement on ordering. So, let's go ahead and move that into our file.
      11. Let's migrate the p 3000:3000 part of the command by defining the ports for the service. We will use the short syntax here, but there is also a more verbose long syntax available as well.
      12. Next, we'll migrate both the working directory (w /app) and the volume mapping (v "$(pwd):/app") by using the working_dir and volumes definitions. Volumes also has a short and long syntax.
        1. One advantage of Docker Compose volume definitions is we can use relative paths from the current directory.
      13. Finally, we need to migrate the environment variable definitions using the environment key.
        1.  

          Defining the MySQL Service

          Now, it's time to define the MySQL service. The command that we used for that container was the following:
          If you are using PowerShell then use this command.
        2. We will first define the new service and name it mysql so it automatically gets the network alias. We'll go ahead and specify the image to use as well.
        3. Next, we'll define the volume mapping. When we ran the container with docker run, the named volume was created automatically. However, that doesn't happen when running with Compose. We need to define the volume in the top-level volumes: section and then specify the mountpoint in the service config. By simply providing only the volume name, the default options are used. There are many more options available though.
        4. Finally, we only need to specify the environment variables.
          At this point, our complete docker-compose.yml should look like this:

          Running our Application Stack

          Now that we have our docker-compose.yml file, we can start it up!
        5. Make sure no other copies of the app/db are running first (docker ps and docker rm -f <ids>).
        6. Start up the application stack using the docker-compose up command. We'll add the d flag to run everything in the background.
          1. docker-compose up -d
            When we run this, we should see output like this:
            You'll notice that the volume was created as well as a network! By default, Docker Compose automatically creates a network specifically for the application stack (which is why we didn't define one in the compose file).
        7. Let's look at the logs using the docker-compose logs -f command. You'll see the logs from each of the services interleaved into a single stream. This is incredibly useful when you want to watch for timing-related issues. The f flag "follows" the log, so will give you live output as it's generated.
          1. If you don't already, you'll see output that looks like this...
            The service name is displayed at the beginning of the line (often colored) to help distinguish messages. If you want to view the logs for a specific service, you can add the service name to the end of the logs command (for example, docker-compose logs -f app).
            Pro tip - Waiting for the DB before starting the app
            When the app is starting up, it actually sits and waits for MySQL to be up and ready before trying to connect to it. Docker doesn't have any built-in support to wait for another container to be fully up, running, and ready before starting another container. For Node-based projects, you can use the wait-port dependency. Similar projects exist for other languages/frameworks.
        8. At this point, you should be able to open your app and see it running. And hey! We're down to a single command!
        9.  
           
           
           
           

        Mount LNMP

         

        composes:

         
         

        Centos8 Install

        Containerd.io

        dnf install https://download.docker.com/linux/centos/7/x86_64/stable/Packages/containerd.io-1.4.3-3.1.el7.x86_64.rpm

        Docker Install

        yum install docker-ce docker-ce-cli
         

        启动Docker,并设置为开机自启

        Docker Compose Install

         
         
         
         

        Host

        ???
         
         
         

        Web

         
         

手动部署

本地项目部署到服务器--docker-nginx
作为web端开发er,几乎从未接触过后端及服务端相关知识。但有些场景下又需要将自己的一些东西从公网(域名)上展示出来,比如自己的可开源项目、博客、简历、demo等。有时候我们可以麻烦后台或者运维同事来帮我们搞一搞,但终究授之以鱼不如授之以渔,在同事的帮助下,我也成功的通过一条简单的途径实现了本地文件上传至服务器并从域名访问。本片博客记录下实现过程。 本实现途径是在linux服务器中安装docker,然后启用docker-nginx代理实现的,希望对与我面对同样困境的小白有所帮助。 第一次接触服务端知识,有错敬请指教,感谢! 那么,开始吧~ 云服务器--CentOS 7.x,低配置即可,如[1核 1GB 1Mbps] 域名--已备案 终端远程工具--如:xshell、FinalShell等 提示:以下命令行内容均在服务器中完成~自行通过终端远程工具连接自己的服务器 1.1 卸载旧版本 如已安装想重新安装,或者是旧版本,则执行。 如已是新版,跳过本步。 $ sudo yum remove docker \ docker-client \ docker-client-latest \ docker-common \ docker-latest \ docker-latest-logrotate \ docker-logrotate \ docker-engine 1.2 使用官方脚本自动安装 以下两种方式任选其一 命令: curl-fsSL https://get.docker.com | bash -s docker --mirror Aliyun 国内 daocloud 命令 curl-sSL https://get.daocloud.io/docker | sh 1.3 启动docker $ sudo systemctl start docker Nginx 是一个高性能的 HTTP 和反向代理 web 服务器,同时也提供了 IMAP/POP3/SMTP 服务 。 docker内安装nginx,作为web服务器来提供我们所需要的的web服务。 2.1 docker查看nginx可用版本 [root@VM_0_10_centos zxm]# docker search nginxNAME DESCRIPTION STARS OFFICIAL AUTOMATEDnginx Official build of Nginx.

1. 安装docker

1.1 卸载旧版本

如已安装想重新安装,或者是旧版本,则执行。 如已是新版,跳过本步。
$ sudo yum remove docker \                  docker-client \                  docker-client-latest \                  docker-common \                  docker-latest \                  docker-latest-logrotate \                  docker-logrotate \                  docker-engine

1.2 使用官方脚本自动安装

以下两种方式任选其一
  • 命令: curl-fsSL https://get.docker.com | bash -s docker --mirror Aliyun
  • 国内 daocloud 命令 curl-sSL https://get.daocloud.io/docker | sh

1.3 启动docker

$ sudo systemctl start docker

2. Docker 安装 Nginx

Nginx 是一个高性能的 HTTP 和反向代理 web 服务器,同时也提供了 IMAP/POP3/SMTP 服务 。 docker内安装nginx,作为web服务器来提供我们所需要的的web服务。

2.1 docker查看nginx可用版本

  • docker search nginx
[root@VM_0_10_centos zxm]# docker search nginxNAME                               DESCRIPTION                                     STARS               OFFICIAL            AUTOMATEDnginx                              Official build of Nginx.                        13333               [OK]                jwilder/nginx-proxy                Automated Nginx reverse proxy for docker con…   1822                                    [OK]richarvey/nginx-php-fpm            Container running Nginx + PHP-FPM capable of777                                     [OK]linuxserver/nginx                  An Nginx container, brought to you by LinuxS…   115                                     bitnami/nginx                      Bitnami nginx Docker Image                      84                                      [OK]tiangolo/nginx-rtmp                Docker image with Nginx using the nginx-rtmp…   75                                      [OK]alfg/nginx-rtmp                    NGINX, nginx-rtmp-module and FFmpeg from sou…   66                                      [OK]......

2.2 安装最新的nginx镜像

$ docker pull nginx:latest

2.3 查看本地镜像

运行命令查看是否安装成功: $ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZEnginx               latest              2622e6cca7eb        5 days ago          132MB
如上,有nginx,成功。
 

3. 创建docker-nginx实例

$ docker run--name[name]-p8080:80-d nginx
  • [name]—— 容器名称
  • [-p 8080:80]—— 端口进行映射,将本地 8080 端口映射到容器内部的 80 端口
  • [-d nginx]—— 设置容器在在后台一直运行
docker run --name nginx -p 8080:80 -d nginx

4. 运行容器

创建容器后默认是运行状态。可以通过 $ docker ps命令查看运行中的容器,通过 $ docker ps-a查看docker的所有容器。 如,我创建的容器名为 zxm-nginx-test,可以在下面容器列表中查看到容器的运行状态及容器信息(id、name等)
[root@VM_0_10_centos zxm]# docker ps -aCONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMESdaad54bac361        nginx               "/docker-entrypoint.…"   41 hours ago        Up About an hour    0.0.0.0:8080->80/tcp   zxm-nginx-test
如果容器未启动,则可以通过 $ docker start[容器name或id]来启动容器。

5. 测试访问

运行容器启动之后,可以通过服务器公网ip地址测试访问。 如: http://[ip]:8080/。 出现页面提示如下,表示成功运行。
 

7. 拷贝文件到docker-nginx容器

首先,我们已经将需要的项目(资源)从本地上传到了服务器上; 然后我们需要做的则是从服务器上的项目资源从目前所在的地方拷贝到docker-nginx容器内,那么我们就需要知道三个东西:
  1. 目标路径
  1. 项目所在路径
  1. docker 拷贝命令
接下来,我们一步一步来。

7.1 查找docker-nginx容器目标文件路径

  • 进入容器: dockerexec-it daad54bac361 bash
$ docker exec -it daad54bac361 bash
docker exec -it 05406627ac75 bash
  • 目录: ls
root@daad54bac361:/# ls
bin  boot  dev  docker-entrypoint.d  docker-entrypoint.sh  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
  • 查找配置文件: cd etc/nginx/conf.d/
root@daad54bac361:/# cd etc/nginx/conf.d/root@daad54bac361:/etc/nginx/conf.d# lsdefault.conf
  • 查看配置文件: cat default.conf
root@daad54bac361:/etc/nginx/conf.d# cat default.conf server {    listen       80;    listen  [::]:80;    server_name  localhost;    #charset koi8-r;    #access_log  /var/log/nginx/host.access.log  main;    location / {        root   /usr/share/nginx/html;        index  index.html index.htm;    }    #error_page  404              /404.html;    ...}
  • 复制(记录)文件中 server>location>root 如: /usr/share/nginx/html 这个目录则是容器的目标目录,接下来则需将其他位置的资源通过docker命令拷贝到该文件目录下。
 
/usr/share/nginx/html
  • 退出容器: exit
root@daad54bac361:/etc/nginx/conf.d# exite xit

7.2 拷贝

  • 先回到刚才本地上传文件至服务器步骤的文件所在服务器位置中
  • cd到该目录下
  • docker命令拷贝到容器中 docker cp[源文件目录][容器id]:[目标目录] 例如,在我的服务器中,想要将 Loading.html传入到容器中,则是: docker cpLoading.html daad54bac361:/usr/share/nginx/html/
 
docker cp index.html 05406627ac75:/usr/share/nginx/html

7.3 完成,访问

浏览器中输入 ip:8080/Loading.html,正常访问到页面,收工~~
 
 
 

8. nginx域名映射配置

以上内容我们完成了基本的服务器项目部署,也就是从公网可以访问自己的项目啦~但是我们不能一直使用公网来访问,不够安全,且不够优雅!那么我们怎么使用域名来访问自己的项目呢? 接下来我们操作一下域名映射。

8.1 docker内安装vim工具

  • 进入docker容器 dockerexec-it[容器id或者name]bash
  • docker内安装vim 依次执行以下命令: apt-getupdate apt-getinstall vim

8.2 配置 default.conf文件

  • cd到配置文件目录
root@daad54bac361:/# cd etc/nginx/conf.d/
root@daad54bac361:/etc/nginx/conf.d# ls
default.conf
  • 编辑default.conf文件: vim default.conf
  • 修改如下: 将 server>server_name的localhost改成自己的域名地址,如我的是 www.zhuxingmin.com,但我可能会设置二级域名等,将 www改成 。则配置如下: server_name*.zhuxingmin.com;
server {    listen       80;    listen  [::]:80;    server_name  *.zhuxingmin.com;    #charset koi8-r;    #access_log  /var/log/nginx/host.access.log  main;    location / {        root   /usr/share/nginx/html;        index  index.html index.htm;    }    ...}
  • 退出容器 exit

8.3 重启docker-nginx容器

docker restart[容器name或id] 如:
[root@VM_0_10_centos zxm]# docker restart zxm-nginx-testzxm-nginx-test[root@VM_0_10_centos zxm]# docker psCONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMESdaad54bac361        nginx               "/docker-entrypoint.…"   40 hours ago        Up 5 seconds        0.0.0.0:8080->80/tcp   zxm-nginx-test

9. 域名解析

  • 前提: 域名已备案
  • 打开域名解析
  • 添加记录(解析)
记录类型:   A主机记录:   test.zhuxingmin.com解析线路:   默认记录值:    服务器公网ipTTL:       10分钟
然后,打开浏览器,输入自己配置的域名,即可访问到docker-nginx容器中的项目啦~~
 
 
 
Docker nginx部署二级域名访问多个web项目
情况是这样的,我借了朋友的阿里云服务器 用docker 部署一下自己的网站(方便管理)。他的服务器自身也用nginx挂了一个网站,端口也用的是默认的80端口。服务器有域名, keep999.cn 我的是docker里面添加的nginx容器,代理的静态网页。docker映射的是8080端口出来,所以,访问的话,需要 keep999.cn:8080 来访问。现在的话,我不想加端口访问了,就想用域名(懒得写端口),于是乎,就要开始想办法解决这个问题了。 [TOC] 学习完这篇文章你将收获: docker创建nginx容器 nginx映射配置文件 网页目录 log目录 docker部署多个web网站 二级域名转发到不同web网站 阿里云设置云解析 具体做法: 一、使用二级域名+转发来访问我的网站 二、使用域名解析 大致方法: docker容器3个nginx容器 1、mynginx 我的网站部署的nginx 端口8080 2、web_nginx 朋友的网站部署的nginx 端口8081 3、proxy_nginx 用于代理转发的nginx 端口80 先说这种方法,是比较理想,比较优质的,统一使用nginx来做入口的代理和转发。 需要注意的是,proxy_nginx的端口,必须是80,不是其他的 。因为你浏览器访问域名,默认不写端口,就是80端口。 配置安全组,我这里直接开放了80【proxy_nginx】、8080-8100【部署多个网站】多个端口 1)docker创建mynginx 部署我的网站 新建一个nginx去把配置文件拷出来供映射的时候使用 自己新建一个目录管理nginx,比如我这里是/mydockerdata/nginx 用这个目录来管理,并创建dist log目录 mkdir log mkdir dist docker ps 查看container 的ID 复制代码 拷贝配置文件到自己的管理目录下面

Loading Comments...