美文网首页
Docker的第一个应用

Docker的第一个应用

作者: halfempty | 来源:发表于2019-04-25 09:25 被阅读0次

    本文参考: https://medium.freecodecamp.org/a-beginners-guide-to-docker-how-to-create-your-first-docker-application-cc03de9b639f

    1. Docker是什么

    Docker可以创建独立且隔离的环境, 换言之, 应用本身实现了跨平台
    简化应用的部署, 且避免同服务器上不同应用之间的干扰

    It allows users to create independent and isolated environments to launch and deploy its applications. These environments are then called containers.

    解决的问题与虚拟机相似, 但实现的机制不同

    Unlike Docker, a virtual machine will include a complete operating system. It will work independently and act like a computer.

    Docker will only share the resources of the host machine in order to run its environments.

    2. 创建Docker应用

    2.1 安装

    通过官方脚本安装

    curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
    

    2.2 创建应用

    新建目录, 目录下包含2文件:

    .
    ├── Dockerfile
    └── main.py
    

    2.3 编辑main.py

    业务代码

    #!/usr/bin/env python3
    
    print("Docker is magic!")
    

    2.4 编辑Dockerfile

    Dockerfile可以理解为应用部署过程

    • 业务程序为python代码, 所以第一步需拉取python运行环境, 默认先从本地查找镜像, 如果没有会去Docker仓库下载
    • 将业务代码添加到/目录
    • 执行业务代码
    # A dockerfile must always start by importing the base image.
    # We use the keyword 'FROM' to do that.
    # In our example, we want import the python image.
    # So we write 'python' for the image name and 'latest' for the version.
    FROM python:latest
    
    # In order to launch our python code, we must import it into our image.
    # We use the keyword 'ADD' to do that.
    # The first parameter 'main.py' is the name of the file on the host.
    # The second parameter '/' is the path where to put the file on the image.
    # Here we put the file at the image root folder.
    ADD main.py /
    
    # We need to define the command to launch when we are going to run the image.
    # We use the keyword 'CMD' to do that.
    # The following command will execute "python ./main.py".
    CMD [ "python", "./main.py" ]
    

    2.5 构建镜像(image)

    -t定义镜像的名称

    $ docker build -t python-test . 
    

    2.6 运行镜像

    $ docker run python-test
    

    3. Docker指令

    # 列出docker镜像
    $ docker image ls
    
    # 删除指定镜像
    $ docker image rm [image name]
    
    # 删除所有镜像
    $ docker image rm $(docker images -a -q)
    
    # 列出所有容器(包括非运行状态的)
    $ docker ps -a
    
    # 停止指定容器
    $ docker stop [container name]
    
    # 停止全部容器
    $ docker stop $(docker ps -a -q)
    
    # 删除全部容器
    $ docker rm $(docker ps -a -q)
    
    # 查看容器日志
    $ docker logs [container name]
    

    相关文章

      网友评论

          本文标题:Docker的第一个应用

          本文链接:https://www.haomeiwen.com/subject/kroogqtx.html