zoukankan      html  css  js  c++  java
  • Docker 命令

    For Client:
    docker exec Run a command in a running container
    docker images List images
    docker import Import the image from a tarball
    docker rm  Remove one or more containers
    docker rmi  Remove one or more images
    docker run  Run a command in a new container
    docker ps  List containers
    docker save Save one or more images to a tar
    docker tag  Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE


    For Registry:
    docker pull Pull an image or a repository from a registry
    docker push Push an image or a repository to a registry


    Extras:
    List tags: curl http://registryserveraddr/v2/imagepath/tag/list  (--cacert ~/cert.crt)
    Delete image: curl -X DELETE imagetagpath
    List all images: curl http://registryserveraddr/v2/_catalog

    docker run -e WWNamespace=dev -e ZKServerAddress=*.*.*.*,*.*.*.*,*.*.*.*  -p 5000:80 5aed1c78f55e

     container

    docker build -t friendlyname .  # Create image using this directory's Dockerfile
    docker run -p 4000:80 friendlyname  # Run "friendlyname" mapping port 4000 to 80
    docker run -d -p 4000:80 friendlyname         # Same thing, but in detached mode
    docker container ls                                # List all running containers
    docker container ls -a             # List all containers, even those not running
    docker container stop <hash>           # Gracefully stop the specified container
    docker container kill <hash>         # Force shutdown of the specified container
    docker container rm <hash>        # Remove specified container from this machine
    docker container rm $(docker container ls -a -q)         # Remove all containers
    docker image ls -a                             # List all images on this machine
    docker image rm <image id>            # Remove specified image from this machine
    docker image rm $(docker image ls -a -q)   # Remove all images from this machine
    docker login             # Log in this CLI session using your Docker credentials
    docker tag <image> username/repository:tag  # Tag <image> for upload to registry
    docker push username/repository:tag            # Upload tagged image to registry
    docker run username/repository:tag                   # Run image from a registry
    

      

    serve

    docker stack ls                                            # List stacks or apps
    docker stack deploy -c <composefile> <appname>  # Run the specified Compose file
    docker service ls                 # List running services associated with an app
    docker service ps <service>                  # List tasks associated with an app
    docker inspect <task or container>                   # Inspect task or container
    docker container ls -q                                      # List container IDs
    docker stack rm <appname>                             # Tear down an application
    docker swarm leave --force      # Take down a single node swarm from the manager
    

      

    swarm

    docker-machine create --driver virtualbox myvm1 # Create a VM (Mac, Win7, Linux)
    docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1 # Win10
    docker-machine env myvm1                # View basic information about your node
    docker-machine ssh myvm1 "docker node ls"         # List the nodes in your swarm
    docker-machine ssh myvm1 "docker node inspect <node ID>"        # Inspect a node
    docker-machine ssh myvm1 "docker swarm join-token -q worker"   # View join token
    docker-machine ssh myvm1   # Open an SSH session with the VM; type "exit" to end
    docker node ls                # View nodes in swarm (while logged on to manager)
    docker-machine ssh myvm2 "docker swarm leave"  # Make the worker leave the swarm
    docker-machine ssh myvm1 "docker swarm leave -f" # Make master leave, kill swarm
    docker-machine ls # list VMs, asterisk shows which VM this shell is talking to
    docker-machine start myvm1            # Start a VM that is currently not running
    docker-machine env myvm1      # show environment variables and command for myvm1
    eval $(docker-machine env myvm1)         # Mac command to connect shell to myvm1
    & "C:Program FilesDockerDockerResourcesindocker-machine.exe" env myvm1 | Invoke-Expression   # Windows command to connect shell to myvm1
    docker stack deploy -c <file> <app>  # Deploy an app; command shell must be set to talk to manager (myvm1), uses local Compose file
    docker-machine scp docker-compose.yml myvm1:~ # Copy file to node's home dir (only required if you use ssh to connect to manager and deploy the app)
    docker-machine ssh myvm1 "docker stack deploy -c <file> <app>"   # Deploy an app using ssh (you must have first copied the Compose file to myvm1)
    eval $(docker-machine env -u)     # Disconnect shell from VMs, use native docker
    docker-machine stop $(docker-machine ls -q)               # Stop all running VMs
    docker-machine rm $(docker-machine ls -q) # Delete all VMs and their disk images
    

      

     应用

    docker-composed 需要release重新生成

     

     

    docker build -t dvm.adsplatformproxy:v1.0.0 .      #build images
    docker run -e WWNamespace=dev -e ZKServerAddress=******  -p 6000:80  6cb913a34ae3    #run container,本地起进程
    docker run -ti 6cb913a34ae3 /bin/bash   #远程进入image文件;exit退出
    docker rmi -f b54d6e186ef4  #远程删除image
    docker rmi -rf b54d6e186ef4
    

      

    docker build -t dvm.adsplatformproxy:v1.0.0 .      #build images
    docker run -e WWNamespace=dev -e ZKServerAddress=******  -p 6000:80  6cb913a34ae3    #run container,本地起进程
    docker run -ti 6cb913a34ae3 /bin/bash   #远程进入image文件;exit退出
    docker rmi -f b54d6e186ef4  #远程删除image
    docker rmi -rf b54d6e186ef4
    

      

    Remove a container

    This will remove the container referenced under the link /redis.

    $ docker rm /redis


    Force-remove a running container

    This command will force-remove a running container.

    $ docker rm --force redis


    The pull command fetches the alpine image from the Docker registry and saves it in our system

    $ docker pull alpine




    run a Docker container based on this image. To do that you are going to use the docker run command.
    docker run alpine ls -l    #it also did a docker pull behind the scenes to download the image.
    docker run alpine echo "hello from alpine"
    docker run alpine /bin/sh
    docker run -it alpine /bin/sh     #Running the run command with the -it flags attaches us to an interactive tty in the container.
     

    What happened? Behind the scenes, a lot of stuff happened. When you call run,

    1. The Docker client contacts the Docker daemon
    2. The Docker daemon checks local store if the image (alpine in this case) is available locally, and if not, dowloads it from Docker Store. (Since we have issued docker pull alpine before, the download step is not necessary)
    3. The Docker daemon creates the container and then runs a command in that container.
    4. The Docker daemon streams the output of the command to the Docker client

     The docker ps command shows you all containers that are currently running.

    docker ps

    a list of all containers that you ran

    docker ps -a

      Notice that the STATUS column shows that these containers exited 

    • Images - The file system and configuration of our application which are used to create containers. To find out more about a Docker image, run docker inspect alpine. In the demo above, you used the docker pull command to download the alpine image. When you executed the command docker run hello-world, it also did a docker pull behind the scenes to download the hello-world image.
    • Containers - Running instances of Docker images — containers run the actual applications. A container includes an application and all of its dependencies. It shares the kernel with other containers, and runs as an isolated process in user space on the host OS. You created a container using docker run which you did using the alpine image that you downloaded. A list of running containers can be seen using the docker ps command.
    • Docker daemon - The background service running on the host that manages building, running and distributing Docker containers.
    • Docker client - The command line tool that allows the user to interact with the Docker daemon.
    • Docker Store - A registry of Docker images, where you can find trusted and enterprise ready containers, plugins, and Docker editions. You'll be using this later in this tutorial.



     Webapps with Docker

    The image that you are going to use is a single-page website that was already created for this demo and is available on the Docker Store as dockersamples/static-site. You can download and run the image directly in one go using docker run as follows.
    docker run -d dockersamples/static-site
    Since the image doesn't exist on your Docker host, the Docker daemon first fetches it from the registry and then runs it as a container.
    In this case, the client didn't tell the Docker Engine to publish any of the ports, so you need to re-run the docker run command to add this instruction.



    Let's re-run the command with some new flags to publish ports and pass your name to the container to customize the message displayed. We'll use the -d option again to run the container in detached mode.
    First, stop the container that you have just launched. In order to do this, we need the container ID.
    Run docker ps to view the running containers.
    docker ps



     Check out the CONTAINER ID column. You will need to use this CONTAINER ID value, a long sequence of characters, to identify the container you want to stop, and then to remove it. 
    $ docker stop a7a0e504ca3e
    $ docker rm   a7a0e504ca3e
    A cool feature is that you do not need to specify the entire CONTAINER ID. You can just specify a few starting characters and if it is unique among all the containers that you have launched, the Docker client will intelligently pick it up.

     
    aunch a container in detached mode
    docker run --name static-site -e AUTHOR="Your Name" -d -P dockersamples/static-site

    In the above command:
    • -d will create a container with the process detached from our terminal
    • -P will publish all the exposed container ports to random ports on the Docker host
    • -e is how you pass environment variables to the container
    • --name allows you to specify a container name
    • AUTHOR is the environment variable name and Your Name is the value that you can pass

    see the ports by running the docker port command.

     docker port static-site
    If you are running Docker for MacDocker for Windows, or Docker on Linux, you can open http://localhost:[YOUR_PORT_FOR 80/tcp]. For our example this is http://localhost:32773.

     

    If you are using Docker Machine on Mac or Windows, you can find the hostname on the command line using docker-machineas follows (assuming you are using the default machine).

    docker-machine ip default
    You can now open http://<YOUR_IPADDRESS>:[YOUR_PORT_FOR 80/tcp] to see your site live! For our example, this is: http://192.168.99.100:32773.



    You can also run a second webserver at the same time, specifying a custom host port mapping to the container's webserver.
    $ docker run --name static-site-2 -e AUTHOR="Your Name" -d -p 8888:80 dockersamples/static-site




    stop and remove the containers since you won't be using them anymore.
    $ docker stop static-site
    $ docker rm static-site


    use a shortcut to remove the second site
    $ docker rm -f static-site-2


    Run docker ps to make sure the containers are gone.
    $ docker ps


     You will build your own image, use that image to run an application locally, and finally, push some of your own images to Docker Cloud.

    Docker images are the basis of containers. In the previous example, you pulled the dockersamples/static-site image from the registry and asked the Docker client to run a container based on that image. To see the list of images that are available locally on your system, run the docker images command.
    $ docker images
     The TAG refers to a particular snapshot of the image and the ID is the corresponding unique identifier for that image.
    For simplicity, you can think of an image akin to a git repository - images can be committed with changes and have multiple versions. When you do not provide a specific version number, the client defaults to latest.


    you could pull a specific version of ubuntu image as follows:
    $ docker pull ubuntu:12.04
    If you do not specify the version number of the image then, as mentioned, the Docker client will default to a version named latest.


    To get a new Docker image you can either get it from a registry (such as the Docker Store) or create your own. There are hundreds of thousands of images available on Docker Store. You can also search for images directly from the command line using docker search.

    An important distinction with regard to images is between base images and child images.

    • Base images are images that have no parent images, usually images with an OS like ubuntu, alpine or debian.

    • Child images are images that build on base images and add additional functionality.

    Another key concept is the idea of official images and user images. (Both of which can be base images or child images.)

    • Official images are Docker sanctioned images. Docker, Inc. sponsors a dedicated team that is responsible for reviewing and publishing all Official Repositories content. This team works in collaboration with upstream software maintainers, security experts, and the broader Docker community. These are not prefixed by an organization or user name. In the list of images above, the pythonnodealpine and nginx images are official (base) images. To find out more about them, check out the Official Images Documentation.

    • User images are images created and shared by users like you. They build on base images and add additional functionality. Typically these are formatted as user/image-name. The user value in the image name is your Docker Store user or organization name.



    Dockerfile

    We want to create a Docker image with this web app. As mentioned above, all user images are based on a base image. Since our application is written in Python, we will build our own Python image based on Alpine. We'll do that using a Dockerfile.

    Dockerfile is a text file that contains a list of commands that the Docker daemon calls while creating an image. The Dockerfile contains all the information that Docker needs to know to run the app — a base Docker image to run from, location of your project code, any dependencies it has, and what commands to run at start-up.

    It is a simple way to automate the image creation process. The best part is that the commands you write in a Dockerfile are almost identical to their equivalent Linux commands. This means you don't really have to learn new syntax to create your own Dockerfiles.

    1. Create a file called Dockerfile, and add content to it as described below.

    We'll start by specifying our base image, using the FROM keyword:

    FROM alpine:3.5
    1. The next step usually is to write the commands of copying the files and installing the dependencies. But first we will install the Python pip package to the alpine linux distribution. This will not just install the pip package but any other dependencies too, which includes the python interpreter. Add the following RUN command next:
    RUN apk add --update py2-pip
    1. Let's add the files that make up the Flask Application.

    Install all Python requirements for our app to run. This will be accomplished by adding the lines:

    COPY requirements.txt /usr/src/app/
    RUN pip install --no-cache-dir -r /usr/src/app/requirements.txt

    Copy the files you have created earlier into our image by using COPY command.
    COPY app.py /usr/src/app/
    COPY templates/index.html /usr/src/app/templates/
    1. Specify the port number which needs to be exposed. Since our flask app is running on 5000 that's what we'll expose.
    EXPOSE 5000
    1. The last step is the command for running the application which is simply - python ./app.py. Use the CMD command to do that
    CMD ["python", "/usr/src/app/app.py"]
    The primary purpose of CMD is to tell the container which command it should run by default when it is started.
    1. Verify your Dockerfile.
    # our base image
    FROM alpine:3.5
    
    # Install python and pip
    RUN apk add --update py2-pip
    
    # install Python modules needed by the Python app
    COPY requirements.txt /usr/src/app/
    RUN pip install --no-cache-dir -r /usr/src/app/requirements.txt  #In order to install the Python modules required for our app, we need to create a file called requirements.txt and add the following line to that file:Flask==0.10.1
    
    # copy files required for the app to run
    COPY app.py /usr/src/app/
    COPY templates/index.html /usr/src/app/templates/
    
    # tell the port number the container should expose
    EXPOSE 5000
    
    # run the application
    CMD ["python", "/usr/src/app/app.py"]
    

      

    Build the image

    Now that you have your Dockerfile, you can build your image. The docker build command does the heavy-lifting of creating a docker image from a Dockerfile.

    When you run the docker build command given below, make sure to replace <YOUR_USERNAME> with your username. This username should be the same one you created when registering on Docker Cloud. If you haven't done that yet, please go ahead and create an account.

    The docker build command is quite simple - it takes an optional tag name with the -t flag, and the location of the directory containing the Dockerfile - the . indicates the current directory:

    $ docker build -t <YOUR_USERNAME>/myfirstapp .
    Run docker images and see if your image (<YOUR_USERNAME>/myfirstapp) shows.

    Run your image

    docker run -p 8888:5000 --name myfirstapp YOUR_USERNAME/myfirstapp
    Head over to http://localhost:8888 and your app should be live. Note If you are using Docker Machine, you may need to open up another terminal and determine the container ip address using docker-machine ip default.

    Push your image

     you've created and tested your image, you can push it to Docker Cloud.

    First you have to login to your Docker Cloud account
    docker login


    Enter YOUR_USERNAME and password when prompted.
    docker push YOUR_USERNAME/myfirstapp


    you are done with this container, stop and remove it since you won't be using it again.
    Open another terminal window and execute the following commands:

    $ docker stop myfirstapp
    $ docker rm myfirstapp

    or

    $ docker rm -f myfirstapp



    • FROM starts the Dockerfile. It is a requirement that the Dockerfile must start with the FROM command. Images are created in layers, which means you can use another image as the base image for your own. The FROM command defines your base layer. As arguments, it takes the name of the image. Optionally, you can add the Docker Cloud username of the maintainer and image version, in the format username/imagename:version.

    • RUN is used to build up the Image you're creating. For each RUN command, Docker will run the command then create a new layer of the image. This way you can roll back your image to previous states easily. The syntax for a RUN instruction is to place the full text of the shell command after the RUN (e.g., RUN mkdir /user/local/foo). This will automatically run in a /bin/sh shell. You can define a different shell like this: RUN /bin/bash -c 'mkdir /user/local/foo'

    • COPY copies local files into the container.

    • CMD defines the commands that will run on the Image at start-up. Unlike a RUN, this does not create a new layer for the Image, but simply runs the command. There can only be one CMD per a Dockerfile/Image. If you need to run multiple commands, the best way to do that is to have the CMD run a script. CMD requires that you tell it where to run the command, unlike RUN. So example CMD commands would be:

      CMD ["python", "./app.py"]
    
      CMD ["/bin/bash", "echo", "Hello World"]
    
    • EXPOSE creates a hint for users of an image which ports provide services. It is included in the information which can be retrieved via $ docker inspect <container-id>.

    Note: The EXPOSE command does not actually make any ports accessible to the host! Instead, this requires publishing ports by means of the -p flag when using $ docker run.

    • PUSH pushes your image to Docker Cloud, or alternately to a private registry
     





    Deploying an app to a Swarm

    To complete this section, you will need to have Docker installed on your machine as mentioned in the Setupsection. You'll also need to have git installed. There are many options for installing it. For instance, you can get it from GitHub.

     Clone the repository onto your machine and cd into the directory:
    git clone https://github.com/docker/example-voting-app.git
    cd example-voting-app

    Deploying the app

    For this first stage, we will use existing images that are in Docker Store.

    This app relies on Docker Swarm mode.

    Swarm mode is the cluster management and orchestration features embedded in the Docker engine.

    You can easily deploy to a swarm using a file that declares your desired state for the app.

    Swarm allows you to run your containers on more than one machine.

    In this tutorial, you can run on just one machine, or you can use something like Docker for AWS or Docker for Azure to quickly create a multiple node machine.

    Alternately, you can use Docker Machine to create a number of local nodes on your development machine. See the Swarm Mode lab for more information.

    First, create a Swarm.

    docker swarm init

    you will need a Docker Compose file.
    You don't need Docker Compose installed, though if you are using Docker for Mac or Docker for Windows you have it installed.
    However, docker stack deploy accepts a file in the Docker Compose format. The file you need is in Docker Example Voting App at the root level. It's called docker-stack.yml. You can also just copy and paste it from here

    version: "3"
    services:
    
      redis:
        image: redis:alpine
        ports:
          - "6379"
        networks:
          - frontend
        deploy:
          replicas: 2
          update_config:
            parallelism: 2
            delay: 10s
          restart_policy:
            condition: on-failure
      db:
        image: postgres:9.4
        volumes:
          - db-data:/var/lib/postgresql/data
        networks:
          - backend
        deploy:
          placement:
            constraints: [node.role == manager]
      vote:
        image: dockersamples/examplevotingapp_vote:before
        ports:
          - 5000:80
        networks:
          - frontend
        depends_on:
          - redis
        deploy:
          replicas: 2
          update_config:
            parallelism: 2
          restart_policy:
            condition: on-failure
      result:
        image: dockersamples/examplevotingapp_result:before
        ports:
          - 5001:80
        networks:
          - backend
        depends_on:
          - db
        deploy:
          replicas: 1
          update_config:
            parallelism: 2
            delay: 10s
          restart_policy:
            condition: on-failure
    
      worker:
        image: dockersamples/examplevotingapp_worker
        networks:
          - frontend
          - backend
        deploy:
          mode: replicated
          replicas: 1
          labels: [APP=VOTING]
          restart_policy:
            condition: on-failure
            delay: 10s
            max_attempts: 3
            window: 120s
          placement:
            constraints: [node.role == manager]
    
      visualizer:
        image: dockersamples/visualizer
        ports:
          - "8080:8080"
        stop_grace_period: 1m30s
        volumes:
          - /var/run/docker.sock:/var/run/docker.sock
        deploy:
          placement:
            constraints: [node.role == manager]
    
    networks:
      frontend:
      backend:
    
    volumes:
      db-data:
    

      First deploy it, and then we will look more deeply into the details:

    docker stack deploy --compose-file docker-stack.yml vote
    Creating network vote_frontend
    Creating network vote_backend
    Creating network vote_default
    Creating service vote_vote
    Creating service vote_result
    Creating service vote_worker
    Creating service vote_redis
    Creating service vote_db
    

      to verify your stack has deployed, use docker stack services vote

    docker stack services vote
    ID            NAME         MODE        REPLICAS  IMAGE
    25wo6p7fltyn  vote_db      replicated  1/1       postgres:9.4
    2ot4sz0cgvw3  vote_worker  replicated  1/1       dockersamples/examplevotingapp_worker:latest
    9faz4wbvxpck  vote_redis   replicated  2/2       redis:alpine
    ocm8x2ijtt88  vote_vote    replicated  2/2       dockersamples/examplevotingapp_vote:before
    p1dcwi0fkcbb  vote_result  replicated  2/2       dockersamples/examplevotingapp_result:before
    

      

    If you take a look at docker-stack.yml, you will see that the file defines

    • vote container based on a Python image
    • result container based on a Node.js image
    • redis container based on a redis image, to temporarily store the data.
    • .NET based worker app based on a .NET image
    • Postgres container based on a postgres image

    The Compose file also defines two networks, front-tier and back-tier. Each container is placed on one or two networks.

    Once on those networks, they can access other services on that network in code just by using the name of the service. Services can be on any number of networks.

    Services are isolated on their network. Services are only able to discover each other by name if they are on the same network. To learn more about networking check out the Networking Lab.

    It's important that you use version 3 of compose files, as docker stack deploy won't support use of earlier versions. 

    version: "3"


    It's important that you use version 3 of compose files, as docker stack deploy won't support use of earlier versions. 
    vote:
        image: dockersamples/examplevotingapp_vote:before
        ports:
          - 5000:80
        networks:
          - frontend
        depends_on:
          - redis
        deploy:
          replicas: 2
          update_config:
            parallelism: 2
          restart_policy:
            condition: on-failure
    

    The image key there specifies which image you can use, in this case the image dockersamples/examplevotingapp_vote:before. If you're familiar with Compose, you may know that there's a build key, which builds based on a Dockerfile. However, docker stack deploy does not suppport build, so you need to use pre-built images.

    Much like docker run you will see you can define ports and networks. There's also a depends_on key which allows you to specify that a service is only deployed after another service, in this case vote only deploys after redis.

    The deploy key is new in version 3. It allows you to specify various properties of the deployment to the Swarm. In this case, you are specifying that you want two replicas, that is two containers are deployed on the Swarm. You can specify other properties, like when to restart, what healthcheck to use, placement constraints, resources.



    Test run

    Now that the app is running, you can go to http://localhost:5000 to see:

    NOTE: If you are running this tutorial in a cloud environment like AWS, Azure, Digital Ocean, or GCE you will not have direct access to localhost or 127.0.0.1 via a browser. A work around for this is to leverage ssh port forwarding. Below is an example for Mac OS. Similarly this can be done for Windows and Putty users.
    $ ssh -L 5000:localhost:5000 <ssh-user>@<CLOUD_INSTANCE_IP_ADDRESS>


    Customize the app

    customize the app and redeploy it. We've supplied the same images but with the votes changed from Cats and Dogs to Java and .NET using the after tag. 

    Change the images used

    Going back to docker-stack.yml, change the vote and result images to use the after tag, so they look like this:

    vote:
        image: dockersamples/examplevotingapp_vote:after
        ports:
          - 5000:80
        networks:
          - frontend
        depends_on:
          - redis
        deploy:
          replicas: 2
          update_config:
            parallelism: 2
          restart_policy:
            condition: on-failure
      result:
        image: dockersamples/examplevotingapp_result:after
        ports:
          - 5001:80
        networks:
          - backend
        depends_on:
          - db
        deploy:
          replicas: 2
          update_config:
            parallelism: 2
            delay: 10s
          restart_policy:
            condition: on-failure
    

      

    Redeploy

    Redeployment is the same as deploying

    docker stack deploy --compose-file docker-stack.yml vote

    Another test run

    Now take it for a spin again. Go to the URLs you used in section 3.1 and see the new votes.

    Remove the stack

    Remove the stack from the swarm.

    docker stack rm vote
     


    For the latest (as of 2015-07-31) version of Registry V2, you can get this image from DockerHub:

    docker pull distribution/registry:master
    

    List all repositories (effectively images):

    curl -X GET https://myregistry:5000/v2/_catalog
    > {"repositories":["redis","ubuntu"]}
    

    List all tags for a repository:

    curl -X GET https://myregistry:5000/v2/ubuntu/tags/list
    > {"name":"ubuntu","tags":["14.04"]}
     
  • 相关阅读:
    IDEA:Application Server was not connected before run configuration stop, reason: Unable to ping 1099
    Module.exports和exports的区别
    [转]aliyun阿里云Maven仓库地址——加速你的maven构建
    使用meld作为git的辅助工具
    vscode中的vue文件中emmet进行tab键不起作用
    JSON.stringify出现 "Converting circular structure to JSON"
    记Javascript一道题的理解
    Javascript类型转换的规则实例解析
    JavaScript中双叹号(!!)作用示例介绍
    typeof / instanceof / constructor / prototype
  • 原文地址:https://www.cnblogs.com/panpanwelcome/p/8125494.html
Copyright © 2011-2022 走看看