├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── es-es └── README.md ├── images ├── change.png ├── click.png ├── commit.png └── edit.png ├── pt-br └── README.md ├── ru └── README.md └── zh-cn └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .idea -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | rvm: 2.2 3 | before_script: gem install awesome_bot 4 | script: awesome_bot README.md --allow-redirect --allow-dupe -w vagrantup.com 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution 4.0 International Public License 58 | 59 | By exercising the Licensed Rights (defined below), You accept and agree 60 | to be bound by the terms and conditions of this Creative Commons 61 | Attribution 4.0 International Public License ("Public License"). To the 62 | extent this Public License may be interpreted as a contract, You are 63 | granted the Licensed Rights in consideration of Your acceptance of 64 | these terms and conditions, and the Licensor grants You such rights in 65 | consideration of benefits the Licensor receives from making the 66 | Licensed Material available under these terms and conditions. 67 | 68 | 69 | Section 1 -- Definitions. 70 | 71 | a. Adapted Material means material subject to Copyright and Similar 72 | Rights that is derived from or based upon the Licensed Material 73 | and in which the Licensed Material is translated, altered, 74 | arranged, transformed, or otherwise modified in a manner requiring 75 | permission under the Copyright and Similar Rights held by the 76 | Licensor. For purposes of this Public License, where the Licensed 77 | Material is a musical work, performance, or sound recording, 78 | Adapted Material is always produced where the Licensed Material is 79 | synched in timed relation with a moving image. 80 | 81 | b. Adapter's License means the license You apply to Your Copyright 82 | and Similar Rights in Your contributions to Adapted Material in 83 | accordance with the terms and conditions of this Public License. 84 | 85 | c. Copyright and Similar Rights means copyright and/or similar rights 86 | closely related to copyright including, without limitation, 87 | performance, broadcast, sound recording, and Sui Generis Database 88 | Rights, without regard to how the rights are labeled or 89 | categorized. For purposes of this Public License, the rights 90 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 91 | Rights. 92 | 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. Share means to provide material to the public by any means or 116 | process that requires permission under the Licensed Rights, such 117 | as reproduction, public display, public performance, distribution, 118 | dissemination, communication, or importation, and to make material 119 | available to the public including in ways that members of the 120 | public may access the material from a place and at a time 121 | individually chosen by them. 122 | 123 | j. Sui Generis Database Rights means rights other than copyright 124 | resulting from Directive 96/9/EC of the European Parliament and of 125 | the Council of 11 March 1996 on the legal protection of databases, 126 | as amended and/or succeeded, as well as other essentially 127 | equivalent rights anywhere in the world. 128 | 129 | k. You means the individual or entity exercising the Licensed Rights 130 | under this Public License. Your has a corresponding meaning. 131 | 132 | 133 | Section 2 -- Scope. 134 | 135 | a. License grant. 136 | 137 | 1. Subject to the terms and conditions of this Public License, 138 | the Licensor hereby grants You a worldwide, royalty-free, 139 | non-sublicensable, non-exclusive, irrevocable license to 140 | exercise the Licensed Rights in the Licensed Material to: 141 | 142 | a. reproduce and Share the Licensed Material, in whole or 143 | in part; and 144 | 145 | b. produce, reproduce, and Share Adapted Material. 146 | 147 | 2. Exceptions and Limitations. For the avoidance of doubt, where 148 | Exceptions and Limitations apply to Your use, this Public 149 | License does not apply, and You do not need to comply with 150 | its terms and conditions. 151 | 152 | 3. Term. The term of this Public License is specified in Section 153 | 6(a). 154 | 155 | 4. Media and formats; technical modifications allowed. The 156 | Licensor authorizes You to exercise the Licensed Rights in 157 | all media and formats whether now known or hereafter created, 158 | and to make technical modifications necessary to do so. The 159 | Licensor waives and/or agrees not to assert any right or 160 | authority to forbid You from making technical modifications 161 | necessary to exercise the Licensed Rights, including 162 | technical modifications necessary to circumvent Effective 163 | Technological Measures. For purposes of this Public License, 164 | simply making modifications authorized by this Section 2(a) 165 | (4) never produces Adapted Material. 166 | 167 | 5. Downstream recipients. 168 | 169 | a. Offer from the Licensor -- Licensed Material. Every 170 | recipient of the Licensed Material automatically 171 | receives an offer from the Licensor to exercise the 172 | Licensed Rights under the terms and conditions of this 173 | Public License. 174 | 175 | b. No downstream restrictions. You may not offer or impose 176 | any additional or different terms or conditions on, or 177 | apply any Effective Technological Measures to, the 178 | Licensed Material if doing so restricts exercise of the 179 | Licensed Rights by any recipient of the Licensed 180 | Material. 181 | 182 | 6. No endorsement. Nothing in this Public License constitutes or 183 | may be construed as permission to assert or imply that You 184 | are, or that Your use of the Licensed Material is, connected 185 | with, or sponsored, endorsed, or granted official status by, 186 | the Licensor or others designated to receive attribution as 187 | provided in Section 3(a)(1)(A)(i). 188 | 189 | b. Other rights. 190 | 191 | 1. Moral rights, such as the right of integrity, are not 192 | licensed under this Public License, nor are publicity, 193 | privacy, and/or other similar personality rights; however, to 194 | the extent possible, the Licensor waives and/or agrees not to 195 | assert any such rights held by the Licensor to the limited 196 | extent necessary to allow You to exercise the Licensed 197 | Rights, but not otherwise. 198 | 199 | 2. Patent and trademark rights are not licensed under this 200 | Public License. 201 | 202 | 3. To the extent possible, the Licensor waives any right to 203 | collect royalties from You for the exercise of the Licensed 204 | Rights, whether directly or through a collecting society 205 | under any voluntary or waivable statutory or compulsory 206 | licensing scheme. In all other cases the Licensor expressly 207 | reserves any right to collect such royalties. 208 | 209 | 210 | Section 3 -- License Conditions. 211 | 212 | Your exercise of the Licensed Rights is expressly made subject to the 213 | following conditions. 214 | 215 | a. Attribution. 216 | 217 | 1. If You Share the Licensed Material (including in modified 218 | form), You must: 219 | 220 | a. retain the following if it is supplied by the Licensor 221 | with the Licensed Material: 222 | 223 | i. identification of the creator(s) of the Licensed 224 | Material and any others designated to receive 225 | attribution, in any reasonable manner requested by 226 | the Licensor (including by pseudonym if 227 | designated); 228 | 229 | ii. a copyright notice; 230 | 231 | iii. a notice that refers to this Public License; 232 | 233 | iv. a notice that refers to the disclaimer of 234 | warranties; 235 | 236 | v. a URI or hyperlink to the Licensed Material to the 237 | extent reasonably practicable; 238 | 239 | b. indicate if You modified the Licensed Material and 240 | retain an indication of any previous modifications; and 241 | 242 | c. indicate the Licensed Material is licensed under this 243 | Public License, and include the text of, or the URI or 244 | hyperlink to, this Public License. 245 | 246 | 2. You may satisfy the conditions in Section 3(a)(1) in any 247 | reasonable manner based on the medium, means, and context in 248 | which You Share the Licensed Material. For example, it may be 249 | reasonable to satisfy the conditions by providing a URI or 250 | hyperlink to a resource that includes the required 251 | information. 252 | 253 | 3. If requested by the Licensor, You must remove any of the 254 | information required by Section 3(a)(1)(A) to the extent 255 | reasonably practicable. 256 | 257 | 4. If You Share Adapted Material You produce, the Adapter's 258 | License You apply must not prevent recipients of the Adapted 259 | Material from complying with this Public License. 260 | 261 | 262 | Section 4 -- Sui Generis Database Rights. 263 | 264 | Where the Licensed Rights include Sui Generis Database Rights that 265 | apply to Your use of the Licensed Material: 266 | 267 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 268 | to extract, reuse, reproduce, and Share all or a substantial 269 | portion of the contents of the database; 270 | 271 | b. if You include all or a substantial portion of the database 272 | contents in a database in which You have Sui Generis Database 273 | Rights, then the database in which You have Sui Generis Database 274 | Rights (but not its individual contents) is Adapted Material; and 275 | 276 | c. You must comply with the conditions in Section 3(a) if You Share 277 | all or a substantial portion of the contents of the database. 278 | 279 | For the avoidance of doubt, this Section 4 supplements and does not 280 | replace Your obligations under this Public License where the Licensed 281 | Rights include other Copyright and Similar Rights. 282 | 283 | 284 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 285 | 286 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 287 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 288 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 289 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 290 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 291 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 292 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 293 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 294 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 295 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 296 | 297 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 298 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 299 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 300 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 301 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 302 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 303 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 304 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 305 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 306 | 307 | c. The disclaimer of warranties and limitation of liability provided 308 | above shall be interpreted in a manner that, to the extent 309 | possible, most closely approximates an absolute disclaimer and 310 | waiver of all liability. 311 | 312 | 313 | Section 6 -- Term and Termination. 314 | 315 | a. This Public License applies for the term of the Copyright and 316 | Similar Rights licensed here. However, if You fail to comply with 317 | this Public License, then Your rights under this Public License 318 | terminate automatically. 319 | 320 | b. Where Your right to use the Licensed Material has terminated under 321 | Section 6(a), it reinstates: 322 | 323 | 1. automatically as of the date the violation is cured, provided 324 | it is cured within 30 days of Your discovery of the 325 | violation; or 326 | 327 | 2. upon express reinstatement by the Licensor. 328 | 329 | For the avoidance of doubt, this Section 6(b) does not affect any 330 | right the Licensor may have to seek remedies for Your violations 331 | of this Public License. 332 | 333 | c. For the avoidance of doubt, the Licensor may also offer the 334 | Licensed Material under separate terms or conditions or stop 335 | distributing the Licensed Material at any time; however, doing so 336 | will not terminate this Public License. 337 | 338 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 339 | License. 340 | 341 | 342 | Section 7 -- Other Terms and Conditions. 343 | 344 | a. The Licensor shall not be bound by any additional or different 345 | terms or conditions communicated by You unless expressly agreed. 346 | 347 | b. Any arrangements, understandings, or agreements regarding the 348 | Licensed Material not stated herein are separate from and 349 | independent of the terms and conditions of this Public License. 350 | 351 | 352 | Section 8 -- Interpretation. 353 | 354 | a. For the avoidance of doubt, this Public License does not, and 355 | shall not be interpreted to, reduce, limit, restrict, or impose 356 | conditions on any use of the Licensed Material that could lawfully 357 | be made without permission under this Public License. 358 | 359 | b. To the extent possible, if any provision of this Public License is 360 | deemed unenforceable, it shall be automatically reformed to the 361 | minimum extent necessary to make it enforceable. If the provision 362 | cannot be reformed, it shall be severed from this Public License 363 | without affecting the enforceability of the remaining terms and 364 | conditions. 365 | 366 | c. No term or condition of this Public License will be waived and no 367 | failure to comply consented to unless expressly agreed to by the 368 | Licensor. 369 | 370 | d. Nothing in this Public License constitutes or may be interpreted 371 | as a limitation upon, or waiver of, any privileges and immunities 372 | that apply to the Licensor or You, including from the legal 373 | processes of any jurisdiction or authority. 374 | 375 | 376 | ======================================================================= 377 | 378 | Creative Commons is not a party to its public 379 | licenses. Notwithstanding, Creative Commons may elect to apply one of 380 | its public licenses to material it publishes and in those instances 381 | will be considered the “Licensor.” The text of the Creative Commons 382 | public licenses is dedicated to the public domain under the CC0 Public 383 | Domain Dedication. Except for the limited purpose of indicating that 384 | material is shared under a Creative Commons public license or as 385 | otherwise permitted by the Creative Commons policies published at 386 | creativecommons.org/policies, Creative Commons does not authorize the 387 | use of the trademark "Creative Commons" or any other trademark or logo 388 | of Creative Commons without its prior written consent including, 389 | without limitation, in connection with any unauthorized modifications 390 | to any of its public licenses or any other arrangements, 391 | understandings, or agreements concerning use of licensed material. For 392 | the avoidance of doubt, this paragraph does not form part of the 393 | public licenses. 394 | 395 | Creative Commons may be contacted at creativecommons.org. 396 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Docker Cheat Sheet 2 | 3 | **Want to improve this cheat sheet? See the [Contributing](#contributing) section!** 4 | 5 | ## Table of Contents 6 | 7 | * [Why Docker](#why-docker) 8 | * [Prerequisites](#prerequisites) 9 | * [Installation](#installation) 10 | * [Containers](#containers) 11 | * [Images](#images) 12 | * [Networks](#networks) 13 | * [Registry and Repository](#registry--repository) 14 | * [Dockerfile](#dockerfile) 15 | * [Layers](#layers) 16 | * [Links](#links) 17 | * [Volumes](#volumes) 18 | * [Exposing Ports](#exposing-ports) 19 | * [Best Practices](#best-practices) 20 | * [Docker-Compose](#docker-compose) 21 | * [Security](#security) 22 | * [Tips](#tips) 23 | * [Contributing](#contributing) 24 | 25 | ## Why Docker 26 | 27 | "With Docker, developers can build any app in any language using any toolchain. “Dockerized” apps are completely portable and can run anywhere - colleagues’ OS X and Windows laptops, QA servers running Ubuntu in the cloud, and production data center VMs running Red Hat. 28 | 29 | Developers can get going quickly by starting with one of the 13,000+ apps available on Docker Hub. Docker manages and tracks changes and dependencies, making it easier for sysadmins to understand how the apps that developers build work. And with Docker Hub, developers can automate their build pipeline and share artifacts with collaborators through public or private repositories. 30 | 31 | Docker helps developers build and ship higher-quality applications, faster." -- [What is Docker](https://www.docker.com/what-docker#copy1) 32 | 33 | ## Prerequisites 34 | 35 | I use [Oh My Zsh](https://github.com/ohmyzsh/oh-my-zsh) with the [Docker plugin](https://github.com/robbyrussell/oh-my-zsh/wiki/Plugins#docker) for autocompletion of docker commands. YMMV. 36 | 37 | ### Linux 38 | 39 | The 3.10.x kernel is [the minimum requirement](https://docs.docker.com/engine/installation/binaries/#check-kernel-dependencies) for Docker. 40 | 41 | ### MacOS 42 | 43 | 10.8 “Mountain Lion” or newer is required. 44 | 45 | ### Windows 10 46 | 47 | Hyper-V must be enabled in BIOS 48 | 49 | VT-D must also be enabled if available (Intel Processors). 50 | 51 | ### Windows Server 52 | 53 | Windows Server 2016 is the minimum version required to install docker and docker-compose. Limitations exist on this version, such as multiple virtual networks and Linux containers. Windows Server 2019 and later are recommended. 54 | 55 | ## Installation 56 | 57 | ### Linux 58 | 59 | Run this quick and easy install script provided by Docker: 60 | 61 | ```sh 62 | curl -sSL https://get.docker.com/ | sh 63 | ``` 64 | 65 | If you're not willing to run a random shell script, please see the [installation](https://docs.docker.com/engine/installation/linux/) instructions for your distribution. 66 | 67 | If you are a complete Docker newbie, you should follow the [series of tutorials](https://docs.docker.com/engine/getstarted/) now. 68 | 69 | ### macOS 70 | 71 | Download and install [Docker Community Edition](https://www.docker.com/community-edition). if you have Homebrew-Cask, just type `brew install --cask docker`. Or Download and install [Docker Toolbox](https://docs.docker.com/toolbox/overview/). [Docker For Mac](https://docs.docker.com/docker-for-mac/) is nice, but it's not quite as finished as the VirtualBox install. [See the comparison](https://docs.docker.com/docker-for-mac/docker-toolbox/). 72 | 73 | > **NOTE** Docker Toolbox is legacy. You should to use Docker Community Edition, See [Docker Toolbox](https://docs.docker.com/toolbox/overview/). 74 | 75 | Once you've installed Docker Community Edition, click the docker icon in Launchpad. Then start up a container: 76 | 77 | ```sh 78 | docker run hello-world 79 | ``` 80 | 81 | That's it, you have a running Docker container. 82 | 83 | If you are a complete Docker newbie, you should probably follow the [series of tutorials](https://docs.docker.com/engine/getstarted/) now. 84 | 85 | ### Windows 10 86 | 87 | Instructions to install Docker Desktop for Windows can be found [here](https://docs.docker.com/desktop/windows/install/) 88 | 89 | Once installed, open powershell as administrator and run: 90 | 91 | ```powershell 92 | # Display the version of docker installed: 93 | docker version 94 | 95 | # Pull, create, and run 'hello-world': 96 | docker run hello-world 97 | ``` 98 | 99 | To continue with this cheat sheet, right click the Docker icon in the system tray, and go to settings. In order to mount volumes, the C:/ drive will need to be enabled in the settings to that information can be passed into the containers (later described in this article). 100 | 101 | To switch between Windows containers and Linux containers, right click the icon in the system tray and click the button to switch container operating system Doing this will stop the current containers that are running, and make them unaccessible until the container OS is switched back. 102 | 103 | Additionally, if you have WSL or WSL2 installed on your desktop, you might want to install the Linux Kernel for Windows. Instructions can be found [here](https://techcommunity.microsoft.com/t5/windows-dev-appconsult/using-wsl2-in-a-docker-linux-container-on-windows-to-run-a/ba-p/1482133). This requires the Windows Subsystem for Linux feature. This will allow for containers to be accessed by WSL operating systems, as well as the efficiency gain from running WSL operating systems in docker. It is also preferred to use [Windows terminal](https://docs.microsoft.com/en-us/windows/terminal/get-started) for this. 104 | 105 | ### Windows Server 2016 / 2019 106 | 107 | Follow Microsoft's instructions that can be found [here](https://docs.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/deploy-containers-on-server#install-docker) 108 | 109 | If using the latest edge version of 2019, be prepared to only work in powershell, as it is only a servercore image (no desktop interface). When starting this machine, it will login and go straight to a powershell window. It is recommended to install text editors and other tools using [Chocolatey](https://chocolatey.org/install). 110 | 111 | After installing, these commands will work: 112 | 113 | ```powershell 114 | # Display the version of docker installed: 115 | docker version 116 | 117 | # Pull, create, and run 'hello-world': 118 | docker run hello-world 119 | ``` 120 | 121 | Windows Server 2016 is not able to run Linux images. 122 | 123 | Windows Server Build 2004 is capable of running both linux and windows containers simultaneously through Hyper-V isolation. When running containers, use the ```--isolation=hyperv``` command, which will isolate the container using a separate kernel instance. 124 | 125 | ### Check Version 126 | 127 | It is very important that you always know the current version of Docker you are currently running on at any point in time. This is very helpful because you get to know what features are compatible with what you have running. This is also important because you know what containers to run from the docker store when you are trying to get template containers. That said let see how to know which version of docker we have running currently. 128 | 129 | * [`docker version`](https://docs.docker.com/engine/reference/commandline/version/) shows which version of docker you have running. 130 | 131 | Get the server version: 132 | 133 | ```console 134 | $ docker version --format '{{.Server.Version}}' 135 | 1.8.0 136 | ``` 137 | 138 | You can also dump raw JSON data: 139 | 140 | ```console 141 | $ docker version --format '{{json .}}' 142 | {"Client":{"Version":"1.8.0","ApiVersion":"1.20","GitCommit":"f5bae0a","GoVersion":"go1.4.2","Os":"linux","Arch":"am"} 143 | ``` 144 | 145 | ## Containers 146 | 147 | [Your basic isolated Docker process](http://etherealmind.com/basics-docker-containers-hypervisors-coreos/). Containers are to Virtual Machines as threads are to processes. Or you can think of them as chroots on steroids. 148 | 149 | ### Lifecycle 150 | 151 | * [`docker create`](https://docs.docker.com/engine/reference/commandline/create) creates a container but does not start it. 152 | * [`docker rename`](https://docs.docker.com/engine/reference/commandline/rename/) allows the container to be renamed. 153 | * [`docker run`](https://docs.docker.com/engine/reference/commandline/run) creates and starts a container in one operation. 154 | * [`docker rm`](https://docs.docker.com/engine/reference/commandline/rm) deletes a container. 155 | * [`docker update`](https://docs.docker.com/engine/reference/commandline/update/) updates a container's resource limits. 156 | 157 | Normally if you run a container without options it will start and stop immediately, if you want keep it running you can use the command, `docker run -td container_id` this will use the option `-t` that will allocate a pseudo-TTY session and `-d` that will detach automatically the container (run container in background and print container ID). 158 | 159 | If you want a transient container, `docker run --rm` will remove the container after it stops. 160 | 161 | If you want to map a directory on the host to a docker container, `docker run -v $HOSTDIR:$DOCKERDIR`. Also see [Volumes](https://github.com/wsargent/docker-cheat-sheet/#volumes). 162 | 163 | If you want to remove also the volumes associated with the container, the deletion of the container must include the `-v` switch like in `docker rm -v`. 164 | 165 | There's also a [logging driver](https://docs.docker.com/engine/admin/logging/overview/) available for individual containers in docker 1.10. To run docker with a custom log driver (i.e., to syslog), use `docker run --log-driver=syslog`. 166 | 167 | Another useful option is `docker run --name yourname docker_image` because when you specify the `--name` inside the run command this will allow you to start and stop a container by calling it with the name the you specified when you created it. 168 | 169 | ### Starting and Stopping 170 | 171 | * [`docker start`](https://docs.docker.com/engine/reference/commandline/start) starts a container so it is running. 172 | * [`docker stop`](https://docs.docker.com/engine/reference/commandline/stop) stops a running container. 173 | * [`docker restart`](https://docs.docker.com/engine/reference/commandline/restart) stops and starts a container. 174 | * [`docker pause`](https://docs.docker.com/engine/reference/commandline/pause/) pauses a running container, "freezing" it in place. 175 | * [`docker unpause`](https://docs.docker.com/engine/reference/commandline/unpause/) will unpause a running container. 176 | * [`docker wait`](https://docs.docker.com/engine/reference/commandline/wait) blocks until running container stops. 177 | * [`docker kill`](https://docs.docker.com/engine/reference/commandline/kill) sends a SIGKILL to a running container. 178 | * [`docker attach`](https://docs.docker.com/engine/reference/commandline/attach) will connect to a running container. 179 | 180 | If you want to detach from a running container, use `Ctrl + p, Ctrl + q`. 181 | If you want to integrate a container with a [host process manager](https://docs.docker.com/engine/admin/host_integration/), start the daemon with `-r=false` then use `docker start -a`. 182 | 183 | If you want to expose container ports through the host, see the [exposing ports](#exposing-ports) section. 184 | 185 | Restart policies on crashed docker instances are [covered here](http://container42.com/2014/09/30/docker-restart-policies/). 186 | 187 | #### CPU Constraints 188 | 189 | You can limit CPU, either using a percentage of all CPUs, or by using specific cores. 190 | 191 | For example, you can tell the [`cpu-shares`](https://docs.docker.com/engine/reference/run/#/cpu-share-constraint) setting. The setting is a bit strange -- 1024 means 100% of the CPU, so if you want the container to take 50% of all CPU cores, you should specify 512. See for more: 192 | 193 | ```sh 194 | docker run -it -c 512 agileek/cpuset-test 195 | ``` 196 | 197 | You can also only use some CPU cores using [`cpuset-cpus`](https://docs.docker.com/engine/reference/run/#/cpuset-constraint). See for details and some nice videos: 198 | 199 | ```sh 200 | docker run -it --cpuset-cpus=0,4,6 agileek/cpuset-test 201 | ``` 202 | 203 | Note that Docker can still **see** all of the CPUs inside the container -- it just isn't using all of them. See for more details. 204 | 205 | #### Memory Constraints 206 | 207 | You can also set [memory constraints](https://docs.docker.com/engine/reference/run/#/user-memory-constraints) on Docker: 208 | 209 | ```sh 210 | docker run -it -m 300M ubuntu:14.04 /bin/bash 211 | ``` 212 | 213 | #### Capabilities 214 | 215 | Linux capabilities can be set by using `cap-add` and `cap-drop`. See for details. This should be used for greater security. 216 | 217 | To mount a FUSE based filesystem, you need to combine both --cap-add and --device: 218 | 219 | ```sh 220 | docker run --rm -it --cap-add SYS_ADMIN --device /dev/fuse sshfs 221 | ``` 222 | 223 | Give access to a single device: 224 | 225 | ```sh 226 | docker run -it --device=/dev/ttyUSB0 debian bash 227 | ``` 228 | 229 | Give access to all devices: 230 | 231 | ```sh 232 | docker run -it --privileged -v /dev/bus/usb:/dev/bus/usb debian bash 233 | ``` 234 | 235 | More info about privileged containers [here]( 236 | https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities). 237 | 238 | ### Info 239 | 240 | * [`docker ps`](https://docs.docker.com/engine/reference/commandline/ps) shows running containers. 241 | * [`docker logs`](https://docs.docker.com/engine/reference/commandline/logs) gets logs from container. (You can use a custom log driver, but logs is only available for `json-file` and `journald` in 1.10). 242 | * [`docker inspect`](https://docs.docker.com/engine/reference/commandline/inspect) looks at all the info on a container (including IP address). 243 | * [`docker events`](https://docs.docker.com/engine/reference/commandline/events) gets events from container. 244 | * [`docker port`](https://docs.docker.com/engine/reference/commandline/port) shows public facing port of container. 245 | * [`docker top`](https://docs.docker.com/engine/reference/commandline/top) shows running processes in container. 246 | * [`docker stats`](https://docs.docker.com/engine/reference/commandline/stats) shows containers' resource usage statistics. 247 | * [`docker diff`](https://docs.docker.com/engine/reference/commandline/diff) shows changed files in the container's FS. 248 | 249 | `docker ps -a` shows running and stopped containers. 250 | 251 | `docker stats --all` shows a list of all containers, default shows just running. 252 | 253 | ### Import / Export 254 | 255 | * [`docker cp`](https://docs.docker.com/engine/reference/commandline/cp) copies files or folders between a container and the local filesystem. 256 | * [`docker export`](https://docs.docker.com/engine/reference/commandline/export) turns container filesystem into tarball archive stream to STDOUT. 257 | 258 | ### Executing Commands 259 | 260 | * [`docker exec`](https://docs.docker.com/engine/reference/commandline/exec) to execute a command in container. 261 | 262 | To enter a running container, attach a new shell process to a running container called foo, use: `docker exec -it foo /bin/bash`. 263 | 264 | ## Images 265 | 266 | Images are just [templates for docker containers](https://docs.docker.com/engine/understanding-docker/#how-does-a-docker-image-work). 267 | 268 | ### Lifecycle 269 | 270 | * [`docker images`](https://docs.docker.com/engine/reference/commandline/images) shows all images. 271 | * [`docker import`](https://docs.docker.com/engine/reference/commandline/import) creates an image from a tarball. 272 | * [`docker build`](https://docs.docker.com/engine/reference/commandline/build) creates image from Dockerfile. 273 | * [`docker commit`](https://docs.docker.com/engine/reference/commandline/commit) creates image from a container, pausing it temporarily if it is running. 274 | * [`docker rmi`](https://docs.docker.com/engine/reference/commandline/rmi) removes an image. 275 | * [`docker load`](https://docs.docker.com/engine/reference/commandline/load) loads an image from a tar archive as STDIN, including images and tags (as of 0.7). 276 | * [`docker save`](https://docs.docker.com/engine/reference/commandline/save) saves an image to a tar archive stream to STDOUT with all parent layers, tags & versions (as of 0.7). 277 | 278 | ### Info 279 | 280 | * [`docker history`](https://docs.docker.com/engine/reference/commandline/history) shows history of image. 281 | * [`docker tag`](https://docs.docker.com/engine/reference/commandline/tag) tags an image to a name (local or registry). 282 | 283 | ### Cleaning up 284 | 285 | While you can use the `docker rmi` command to remove specific images, there's a tool called [docker-gc](https://github.com/spotify/docker-gc) that will safely clean up images that are no longer used by any containers. As of docker 1.13, `docker image prune` is also available for removing unused images. See [Prune](#prune). 286 | 287 | ### Load/Save image 288 | 289 | Load an image from file: 290 | 291 | ```sh 292 | docker load < my_image.tar.gz 293 | ``` 294 | 295 | Save an existing image: 296 | 297 | ```sh 298 | docker save my_image:my_tag | gzip > my_image.tar.gz 299 | ``` 300 | 301 | ### Import/Export container 302 | 303 | Import a container as an image from file: 304 | 305 | ```sh 306 | cat my_container.tar.gz | docker import - my_image:my_tag 307 | ``` 308 | 309 | Export an existing container: 310 | 311 | ```sh 312 | docker export my_container | gzip > my_container.tar.gz 313 | ``` 314 | 315 | ### Difference between loading a saved image and importing an exported container as an image 316 | 317 | Loading an image using the `load` command creates a new image including its history. 318 | Importing a container as an image using the `import` command creates a new image excluding the history which results in a smaller image size compared to loading an image. 319 | 320 | ## Networks 321 | 322 | Docker has a [networks](https://docs.docker.com/engine/userguide/networking/) feature. Docker automatically creates 3 network interfaces when you install it (bridge, host none). A new container is launched into the bridge network by default. To enable communication between multiple containers, you can create a new network and launch containers in it. This enables containers to communicate to each other while being isolated from containers that are not connected to the network. Furthermore, it allows to map container names to their IP addresses. See [working with networks](https://docs.docker.com/engine/userguide/networking/work-with-networks/) for more details. 323 | 324 | ### Lifecycle 325 | 326 | * [`docker network create`](https://docs.docker.com/engine/reference/commandline/network_create/) NAME Create a new network (default type: bridge). 327 | * [`docker network rm`](https://docs.docker.com/engine/reference/commandline/network_rm/) NAME Remove one or more networks by name or identifier. No containers can be connected to the network when deleting it. 328 | 329 | ### Info 330 | 331 | * [`docker network ls`](https://docs.docker.com/engine/reference/commandline/network_ls/) List networks 332 | * [`docker network inspect`](https://docs.docker.com/engine/reference/commandline/network_inspect/) NAME Display detailed information on one or more networks. 333 | 334 | ### Connection 335 | 336 | * [`docker network connect`](https://docs.docker.com/engine/reference/commandline/network_connect/) NETWORK CONTAINER Connect a container to a network 337 | * [`docker network disconnect`](https://docs.docker.com/engine/reference/commandline/network_disconnect/) NETWORK CONTAINER Disconnect a container from a network 338 | 339 | You can specify a [specific IP address for a container](https://blog.jessfraz.com/post/ips-for-all-the-things/): 340 | 341 | ```sh 342 | # create a new bridge network with your subnet and gateway for your ip block 343 | docker network create --subnet 203.0.113.0/24 --gateway 203.0.113.254 iptastic 344 | 345 | # run a nginx container with a specific ip in that block 346 | $ docker run --rm -it --net iptastic --ip 203.0.113.2 nginx 347 | 348 | # curl the ip from any other place (assuming this is a public ip block duh) 349 | $ curl 203.0.113.2 350 | ``` 351 | 352 | ## Registry & Repository 353 | 354 | A repository is a *hosted* collection of tagged images that together create the file system for a container. 355 | 356 | A registry is a *host* -- a server that stores repositories and provides an HTTP API for [managing the uploading and downloading of repositories](https://docs.docker.com/engine/tutorials/dockerrepos/). 357 | 358 | Docker.com hosts its own [index](https://hub.docker.com/) to a central registry which contains a large number of repositories. Having said that, the central docker registry [does not do a good job of verifying images](https://titanous.com/posts/docker-insecurity) and should be avoided if you're worried about security. 359 | 360 | * [`docker login`](https://docs.docker.com/engine/reference/commandline/login) to login to a registry. 361 | * [`docker logout`](https://docs.docker.com/engine/reference/commandline/logout) to logout from a registry. 362 | * [`docker search`](https://docs.docker.com/engine/reference/commandline/search) searches registry for image. 363 | * [`docker pull`](https://docs.docker.com/engine/reference/commandline/pull) pulls an image from registry to local machine. 364 | * [`docker push`](https://docs.docker.com/engine/reference/commandline/push) pushes an image to the registry from local machine. 365 | 366 | ### Run local registry 367 | 368 | You can run a local registry by using the [docker distribution](https://github.com/docker/distribution) project and looking at the [local deploy](https://github.com/docker/docker.github.io/blob/master/registry/deploying.md) instructions. 369 | 370 | Also see the [mailing list](https://groups.google.com/a/dockerproject.org/forum/#!forum/distribution). 371 | 372 | ## Dockerfile 373 | 374 | [The configuration file](https://docs.docker.com/engine/reference/builder/). Sets up a Docker container when you run `docker build` on it. Vastly preferable to `docker commit`. 375 | 376 | Here are some common text editors and their syntax highlighting modules you could use to create Dockerfiles: 377 | 378 | * If you use [jEdit](http://jedit.org), I've put up a syntax highlighting module for [Dockerfile](https://github.com/wsargent/jedit-docker-mode) you can use. 379 | * [Sublime Text 2](https://packagecontrol.io/packages/Dockerfile%20Syntax%20Highlighting) 380 | * [Atom](https://atom.io/packages/language-docker) 381 | * [Vim](https://github.com/ekalinin/Dockerfile.vim) 382 | * [Emacs](https://github.com/spotify/dockerfile-mode) 383 | * [TextMate](https://github.com/docker/docker/tree/master/contrib/syntax/textmate) 384 | * [VS Code](https://github.com/Microsoft/vscode-docker) 385 | * Also see [Docker meets the IDE](https://domeide.github.io/) 386 | 387 | ### Instructions 388 | 389 | * [.dockerignore](https://docs.docker.com/engine/reference/builder/#dockerignore-file) 390 | * [FROM](https://docs.docker.com/engine/reference/builder/#from) Sets the Base Image for subsequent instructions. 391 | * [MAINTAINER (deprecated - use LABEL instead)](https://docs.docker.com/engine/reference/builder/#maintainer-deprecated) Set the Author field of the generated images. 392 | * [RUN](https://docs.docker.com/engine/reference/builder/#run) execute any commands in a new layer on top of the current image and commit the results. 393 | * [CMD](https://docs.docker.com/engine/reference/builder/#cmd) provide defaults for an executing container. 394 | * [EXPOSE](https://docs.docker.com/engine/reference/builder/#expose) informs Docker that the container listens on the specified network ports at runtime. NOTE: does not actually make ports accessible. 395 | * [ENV](https://docs.docker.com/engine/reference/builder/#env) sets environment variable. 396 | * [ADD](https://docs.docker.com/engine/reference/builder/#add) copies new files, directories or remote file to container. Invalidates caches. Avoid `ADD` and use `COPY` instead. 397 | * [COPY](https://docs.docker.com/engine/reference/builder/#copy) copies new files or directories to container. By default this copies as root regardless of the USER/WORKDIR settings. Use `--chown=:` to give ownership to another user/group. (Same for `ADD`.) 398 | * [ENTRYPOINT](https://docs.docker.com/engine/reference/builder/#entrypoint) configures a container that will run as an executable. 399 | * [VOLUME](https://docs.docker.com/engine/reference/builder/#volume) creates a mount point for externally mounted volumes or other containers. 400 | * [USER](https://docs.docker.com/engine/reference/builder/#user) sets the user name for following RUN / CMD / ENTRYPOINT commands. 401 | * [WORKDIR](https://docs.docker.com/engine/reference/builder/#workdir) sets the working directory. 402 | * [ARG](https://docs.docker.com/engine/reference/builder/#arg) defines a build-time variable. 403 | * [ONBUILD](https://docs.docker.com/engine/reference/builder/#onbuild) adds a trigger instruction when the image is used as the base for another build. 404 | * [STOPSIGNAL](https://docs.docker.com/engine/reference/builder/#stopsignal) sets the system call signal that will be sent to the container to exit. 405 | * [LABEL](https://docs.docker.com/config/labels-custom-metadata/) apply key/value metadata to your images, containers, or daemons. 406 | * [SHELL](https://docs.docker.com/engine/reference/builder/#shell) override default shell is used by docker to run commands. 407 | * [HEALTHCHECK](https://docs.docker.com/engine/reference/builder/#healthcheck) tells docker how to test a container to check that it is still working. 408 | 409 | ### Tutorial 410 | 411 | * [Flux7's Dockerfile Tutorial](https://www.flux7.com/tutorial/docker-tutorial-series-part-3-automation-is-the-word-using-dockerfile/) 412 | 413 | ### Examples 414 | 415 | * [Examples](https://docs.docker.com/engine/reference/builder/#dockerfile-examples) 416 | * [Best practices for writing Dockerfiles](https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/) 417 | * [Michael Crosby](http://crosbymichael.com/) has some more [Dockerfiles best practices](http://crosbymichael.com/dockerfile-best-practices.html) / [take 2](http://crosbymichael.com/dockerfile-best-practices-take-2.html). 418 | * [Building Good Docker Images](http://jonathan.bergknoff.com/journal/building-good-docker-images) / [Building Better Docker Images](http://jonathan.bergknoff.com/journal/building-better-docker-images) 419 | * [Managing Container Configuration with Metadata](https://speakerdeck.com/garethr/managing-container-configuration-with-metadata) 420 | * [How to write excellent Dockerfiles](https://rock-it.pl/how-to-write-excellent-dockerfiles/) 421 | 422 | ## Layers 423 | 424 | The versioned filesystem in Docker is based on layers. They're like [git commits or changesets for filesystems](https://docs.docker.com/engine/userguide/storagedriver/imagesandcontainers/). 425 | 426 | ## Links 427 | 428 | Links are how Docker containers talk to each other [through TCP/IP ports](https://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/). [Atlassian](https://blogs.atlassian.com/2013/11/docker-all-the-things-at-atlassian-automation-and-wiring/) show worked examples. You can also resolve [links by hostname](https://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/#/updating-the-etchosts-file). 429 | 430 | This has been deprecated to some extent by [user-defined networks](https://docs.docker.com/network/). 431 | 432 | NOTE: If you want containers to ONLY communicate with each other through links, start the docker daemon with `-icc=false` to disable inter process communication. 433 | 434 | If you have a container with the name CONTAINER (specified by `docker run --name CONTAINER`) and in the Dockerfile, it has an exposed port: 435 | 436 | ``` 437 | EXPOSE 1337 438 | ``` 439 | 440 | Then if we create another container called LINKED like so: 441 | 442 | ```sh 443 | docker run -d --link CONTAINER:ALIAS --name LINKED user/wordpress 444 | ``` 445 | 446 | Then the exposed ports and aliases of CONTAINER will show up in LINKED with the following environment variables: 447 | 448 | ```sh 449 | $ALIAS_PORT_1337_TCP_PORT 450 | $ALIAS_PORT_1337_TCP_ADDR 451 | ``` 452 | 453 | And you can connect to it that way. 454 | 455 | To delete links, use `docker rm --link`. 456 | 457 | Generally, linking between docker services is a subset of "service discovery", a big problem if you're planning to use Docker at scale in production. Please read [The Docker Ecosystem: Service Discovery and Distributed Configuration Stores](https://www.digitalocean.com/community/tutorials/the-docker-ecosystem-service-discovery-and-distributed-configuration-stores) for more info. 458 | 459 | ## Volumes 460 | 461 | Docker volumes are [free-floating filesystems](https://docs.docker.com/engine/tutorials/dockervolumes/). They don't have to be connected to a particular container. You can use volumes mounted from [data-only containers](https://medium.com/@ramangupta/why-docker-data-containers-are-good-589b3c6c749e) for portability. As of Docker 1.9.0, Docker has named volumes which replace data-only containers. Consider using named volumes to implement it rather than data containers. 462 | 463 | ### Lifecycle 464 | 465 | * [`docker volume create`](https://docs.docker.com/engine/reference/commandline/volume_create/) 466 | * [`docker volume rm`](https://docs.docker.com/engine/reference/commandline/volume_rm/) 467 | 468 | ### Info 469 | 470 | * [`docker volume ls`](https://docs.docker.com/engine/reference/commandline/volume_ls/) 471 | * [`docker volume inspect`](https://docs.docker.com/engine/reference/commandline/volume_inspect/) 472 | 473 | Volumes are useful in situations where you can't use links (which are TCP/IP only). For instance, if you need to have two docker instances communicate by leaving stuff on the filesystem. 474 | 475 | You can mount them in several docker containers at once, using `docker run --volumes-from`. 476 | 477 | Because volumes are isolated filesystems, they are often used to store state from computations between transient containers. That is, you can have a stateless and transient container run from a recipe, blow it away, and then have a second instance of the transient container pick up from where the last one left off. 478 | 479 | See [advanced volumes](http://crosbymichael.com/advanced-docker-volumes.html) for more details. [Container42](http://container42.com/2014/11/03/docker-indepth-volumes/) is also helpful. 480 | 481 | You can [map MacOS host directories as docker volumes](https://docs.docker.com/engine/tutorials/dockervolumes/#mount-a-host-directory-as-a-data-volume): 482 | 483 | ```sh 484 | docker run -v /Users/wsargent/myapp/src:/src 485 | ``` 486 | 487 | You can use remote NFS volumes if you're [feeling brave](https://docs.docker.com/engine/tutorials/dockervolumes/#/mount-a-shared-storage-volume-as-a-data-volume). 488 | 489 | You may also consider running data-only containers as described [here](http://container42.com/2013/12/16/persistent-volumes-with-docker-container-as-volume-pattern/) to provide some data portability. 490 | 491 | Be aware that you can [mount files as volumes](#volumes-can-be-files). 492 | 493 | ## Exposing ports 494 | 495 | Exposing incoming ports through the host container is [fiddly but doable](https://docs.docker.com/engine/reference/run/#expose-incoming-ports). 496 | 497 | This is done by mapping the container port to the host port (only using localhost interface) using `-p`: 498 | 499 | ```sh 500 | docker run -p 127.0.0.1:$HOSTPORT:$CONTAINERPORT \ 501 | --name CONTAINER \ 502 | -t someimage 503 | ``` 504 | 505 | You can tell Docker that the container listens on the specified network ports at runtime by using [EXPOSE](https://docs.docker.com/engine/reference/builder/#expose): 506 | 507 | ```Dockerfile 508 | EXPOSE 509 | ``` 510 | 511 | Note that `EXPOSE` does not expose the port itself - only `-p` will do that. 512 | 513 | To expose the container's port on your localhost's port, run: 514 | 515 | ```sh 516 | iptables -t nat -A DOCKER -p tcp --dport -j DNAT --to-destination : 517 | ``` 518 | 519 | If you're running Docker in Virtualbox, you then need to forward the port there as well, using [forwarded_port](https://docs.vagrantup.com/v2/networking/forwarded_ports.html). Define a range of ports in your Vagrantfile like this so you can dynamically map them: 520 | 521 | ``` 522 | Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| 523 | ... 524 | 525 | (49000..49900).each do |port| 526 | config.vm.network :forwarded_port, :host => port, :guest => port 527 | end 528 | 529 | ... 530 | end 531 | ``` 532 | 533 | If you forget what you mapped the port to on the host container, use `docker port` to show it: 534 | 535 | ```sh 536 | docker port CONTAINER $CONTAINERPORT 537 | ``` 538 | 539 | ## Best Practices 540 | 541 | This is where general Docker best practices and war stories go: 542 | 543 | * [The Rabbit Hole of Using Docker in Automated Tests](http://gregoryszorc.com/blog/2014/10/16/the-rabbit-hole-of-using-docker-in-automated-tests/) 544 | * [Bridget Kromhout](https://twitter.com/bridgetkromhout) has a useful blog post on [running Docker in production](http://sysadvent.blogspot.co.uk/2014/12/day-1-docker-in-production-reality-not.html) at Dramafever. 545 | * There's also a best practices [blog post](http://developers.lyst.com/devops/2014/12/08/docker/) from Lyst. 546 | * [Building a Development Environment With Docker](https://tersesystems.com/2013/11/20/building-a-development-environment-with-docker/) 547 | * [Discourse in a Docker Container](https://samsaffron.com/archive/2013/11/07/discourse-in-a-docker-container) 548 | 549 | ## Docker-Compose 550 | 551 | Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration. To learn more about all the features of Compose, see the [list of features](https://docs.docker.com/compose/overview/#features). 552 | 553 | By using the following command you can start up your application: 554 | 555 | ```sh 556 | docker-compose -f up 557 | ``` 558 | 559 | You can also run docker-compose in detached mode using -d flag, then you can stop it whenever needed by the following command: 560 | 561 | ```sh 562 | docker-compose stop 563 | ``` 564 | 565 | You can bring everything down, removing the containers entirely, with the down command. Pass `--volumes` to also remove the data volume. 566 | 567 | ## Security 568 | 569 | This is where security tips about Docker go. The Docker [security](https://docs.docker.com/engine/security/security/) page goes into more detail. 570 | 571 | First things first: Docker runs as root. If you are in the `docker` group, you effectively [have root access](https://web.archive.org/web/20161226211755/http://reventlov.com/advisories/using-the-docker-command-to-root-the-host). If you expose the docker unix socket to a container, you are giving the container [root access to the host](https://www.lvh.io/posts/dont-expose-the-docker-socket-not-even-to-a-container/). 572 | 573 | Docker should not be your only defense. You should secure and harden it. 574 | 575 | For an understanding of what containers leave exposed, you should read [Understanding and Hardening Linux Containers](https://www.nccgroup.trust/globalassets/our-research/us/whitepapers/2016/april/ncc_group_understanding_hardening_linux_containers-1-1.pdf) by [Aaron Grattafiori](https://twitter.com/dyn___). This is a complete and comprehensive guide to the issues involved with containers, with a plethora of links and footnotes leading on to yet more useful content. The security tips following are useful if you've already hardened containers in the past, but are not a substitute for understanding. 576 | 577 | ### Security Tips 578 | 579 | For greatest security, you want to run Docker inside a virtual machine. This is straight from the Docker Security Team Lead -- [slides](http://www.slideshare.net/jpetazzo/linux-containers-lxc-docker-and-security) / [notes](http://www.projectatomic.io/blog/2014/08/is-it-safe-a-look-at-docker-and-security-from-linuxcon/). Then, run with AppArmor / seccomp / SELinux / grsec etc to [limit the container permissions](http://linux-audit.com/docker-security-best-practices-for-your-vessel-and-containers/). See the [Docker 1.10 security features](https://blog.docker.com/2016/02/docker-engine-1-10-security/) for more details. 580 | 581 | Docker image ids are [sensitive information](https://medium.com/@quayio/your-docker-image-ids-are-secrets-and-its-time-you-treated-them-that-way-f55e9f14c1a4) and should not be exposed to the outside world. Treat them like passwords. 582 | 583 | See the [Docker Security Cheat Sheet](https://github.com/konstruktoid/Docker/blob/master/Security/CheatSheet.adoc) by [Thomas Sjögren](https://github.com/konstruktoid): some good stuff about container hardening in there. 584 | 585 | Check out the [docker bench security script](https://github.com/docker/docker-bench-security), download the [white papers](https://blog.docker.com/2015/05/understanding-docker-security-and-best-practices/). 586 | 587 | Snyk's [10 Docker Image Security Best Practices cheat sheet](https://snyk.io/blog/10-docker-image-security-best-practices/) 588 | 589 | You should start off by using a kernel with unstable patches for grsecurity / pax compiled in, such as [Alpine Linux](https://en.wikipedia.org/wiki/Alpine_Linux). If you are using grsecurity in production, you should spring for [commercial support](https://grsecurity.net/business_support.php) for the [stable patches](https://grsecurity.net/announce.php), same as you would do for RedHat. It's $200 a month, which is nothing to your devops budget. 590 | 591 | Since docker 1.11 you can easily limit the number of active processes running inside a container to prevent fork bombs. This requires a linux kernel >= 4.3 with CGROUP_PIDS=y to be in the kernel configuration. 592 | 593 | ```sb 594 | docker run --pids-limit=64 595 | ``` 596 | 597 | Also available since docker 1.11 is the ability to prevent processes from gaining new privileges. This feature have been in the linux kernel since version 3.5. You can read more about it in [this](http://www.projectatomic.io/blog/2016/03/no-new-privs-docker/) blog post. 598 | 599 | ```sh 600 | docker run --security-opt=no-new-privileges 601 | ``` 602 | 603 | From the [Docker Security Cheat Sheet](http://container-solutions.com/content/uploads/2015/06/15.06.15_DockerCheatSheet_A2.pdf) (it's in PDF which makes it hard to use, so copying below) by [Container Solutions](http://container-solutions.com/is-docker-safe-for-production/): 604 | 605 | Turn off interprocess communication with: 606 | 607 | ```sh 608 | docker -d --icc=false --iptables 609 | ``` 610 | 611 | Set the container to be read-only: 612 | 613 | ```sh 614 | docker run --read-only 615 | ``` 616 | 617 | Verify images with a hashsum: 618 | 619 | ```sh 620 | docker pull debian@sha256:a25306f3850e1bd44541976aa7b5fd0a29be 621 | ``` 622 | 623 | Set volumes to be read only: 624 | 625 | ```sh 626 | docker run -v $(pwd)/secrets:/secrets:ro debian 627 | ``` 628 | 629 | Define and run a user in your Dockerfile so you don't run as root inside the container: 630 | 631 | ```Dockerfile 632 | RUN groupadd -r user && useradd -r -g user user 633 | USER user 634 | ``` 635 | 636 | ### User Namespaces 637 | 638 | There's also work on [user namespaces](https://s3hh.wordpress.com/2013/07/19/creating-and-using-containers-without-privilege/) -- it is in 1.10 but is not enabled by default. 639 | 640 | To enable user namespaces ("remap the userns") in Ubuntu 15.10, [follow the blog example](https://raesene.github.io/blog/2016/02/04/Docker-User-Namespaces/). 641 | 642 | ### Security Videos 643 | 644 | * [Using Docker Safely](https://youtu.be/04LOuMgNj9U) 645 | * [Securing your applications using Docker](https://youtu.be/KmxOXmPhZbk) 646 | * [Container security: Do containers actually contain?](https://youtu.be/a9lE9Urr6AQ) 647 | * [Linux Containers: Future or Fantasy?](https://www.youtube.com/watch?v=iN6QbszB1R8) 648 | 649 | ### Security Roadmap 650 | 651 | The Docker roadmap talks about [seccomp support](https://github.com/docker/docker/blob/master/ROADMAP.md#11-security). 652 | There is an AppArmor policy generator called [bane](https://github.com/jfrazelle/bane), and they're working on [security profiles](https://github.com/docker/docker/issues/17142). 653 | 654 | ## Tips 655 | 656 | Sources: 657 | 658 | * [15 Docker Tips in 5 minutes](http://sssslide.com/speakerdeck.com/bmorearty/15-docker-tips-in-5-minutes) 659 | * [CodeFresh Everyday Hacks Docker](https://codefresh.io/blog/everyday-hacks-docker/) 660 | 661 | ### Prune 662 | 663 | The new [Data Management Commands](https://github.com/docker/docker/pull/26108) have landed as of Docker 1.13: 664 | 665 | * `docker system prune` 666 | * `docker volume prune` 667 | * `docker network prune` 668 | * `docker container prune` 669 | * `docker image prune` 670 | 671 | ### df 672 | 673 | `docker system df` presents a summary of the space currently used by different docker objects. 674 | 675 | ### Heredoc Docker Container 676 | 677 | ```sh 678 | docker build -t htop - << EOF 679 | FROM alpine 680 | RUN apk --no-cache add htop 681 | EOF 682 | ``` 683 | 684 | ### Last IDs 685 | 686 | ```sh 687 | alias dl='docker ps -l -q' 688 | docker run ubuntu echo hello world 689 | docker commit $(dl) helloworld 690 | ``` 691 | 692 | ### Commit with command (needs Dockerfile) 693 | 694 | ```sh 695 | docker commit -run='{"Cmd":["postgres", "-too -many -opts"]}' $(dl) postgres 696 | ``` 697 | 698 | ### Get IP address 699 | 700 | ```sh 701 | docker inspect $(dl) | grep -wm1 IPAddress | cut -d '"' -f 4 702 | ``` 703 | 704 | Or with [jq](https://stedolan.github.io/jq/) installed: 705 | 706 | ```sh 707 | docker inspect $(dl) | jq -r '.[0].NetworkSettings.IPAddress' 708 | ``` 709 | 710 | Or using a [go template](https://docs.docker.com/engine/reference/commandline/inspect): 711 | 712 | ```sh 713 | docker inspect -f '{{ .NetworkSettings.IPAddress }}' 714 | ``` 715 | 716 | Or when building an image from Dockerfile, when you want to pass in a build argument: 717 | 718 | ```sh 719 | DOCKER_HOST_IP=`ifconfig | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" | grep -v 127.0.0.1 | awk '{ print $2 }' | cut -f2 -d: | head -n1` 720 | echo DOCKER_HOST_IP = $DOCKER_HOST_IP 721 | docker build \ 722 | --build-arg ARTIFACTORY_ADDRESS=$DOCKER_HOST_IP 723 | -t sometag \ 724 | some-directory/ 725 | ``` 726 | 727 | ### Get port mapping 728 | 729 | ```sh 730 | docker inspect -f '{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' 731 | ``` 732 | 733 | ### Find containers by regular expression 734 | 735 | ```sh 736 | for i in $(docker ps -a | grep "REGEXP_PATTERN" | cut -f1 -d" "); do echo $i; done 737 | ``` 738 | 739 | ### Get Environment Settings 740 | 741 | ```sh 742 | docker run --rm ubuntu env 743 | ``` 744 | 745 | ### Kill running containers 746 | 747 | ```sh 748 | if [ "$(docker ps -q)" ]; then docker kill $(docker ps -q); else echo "No running containers."; fi 749 | 750 | ``` 751 | 752 | ### Delete all containers (force!! running or stopped containers) 753 | 754 | ```sh 755 | if [ "$(docker ps -qa)" ]; then docker rm -f $(docker ps -qa); else echo "No containers to delete."; fi 756 | 757 | ``` 758 | 759 | ### Delete old containers 760 | 761 | ```sh 762 | docker ps -a | grep 'weeks ago' | awk '{print $1}' | xargs docker rm 763 | ``` 764 | 765 | ### Delete stopped containers 766 | 767 | ```sh 768 | docker rm -v $(docker ps -a -q -f status=exited) 769 | ``` 770 | 771 | ### Delete containers after stopping 772 | 773 | ```sh 774 | docker stop $(docker ps -aq) && docker rm -v $(docker ps -aq) 775 | ``` 776 | 777 | ### Delete dangling images 778 | 779 | ```sh 780 | docker rmi $(docker images -q -f dangling=true) 781 | ``` 782 | 783 | ### Delete all images 784 | 785 | ```sh 786 | docker rmi $(docker images -q) 787 | ``` 788 | 789 | ### Delete dangling volumes 790 | 791 | As of Docker 1.9: 792 | 793 | ```sh 794 | docker volume rm $(docker volume ls -q -f dangling=true) 795 | ``` 796 | 797 | In 1.9.0, the filter `dangling=false` does _not_ work - it is ignored and will list all volumes. 798 | 799 | ### Show image dependencies 800 | 801 | ```sh 802 | docker images -viz | dot -Tpng -o docker.png 803 | ``` 804 | 805 | ### Slimming down Docker containers 806 | 807 | - Cleaning APT in a `RUN` layer - This should be done in the same layer as other `apt` commands. Otherwise, the previous layers still persist the original information and your images will still be fat. 808 | ```Dockerfile 809 | RUN {apt commands} \ 810 | && apt-get clean \ 811 | && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* 812 | ``` 813 | - Flatten an image 814 | ```sh 815 | ID=$(docker run -d image-name /bin/bash) 816 | docker export $ID | docker import – flat-image-name 817 | ``` 818 | - For backup 819 | ```sh 820 | ID=$(docker run -d image-name /bin/bash) 821 | (docker export $ID | gzip -c > image.tgz) 822 | gzip -dc image.tgz | docker import - flat-image-name 823 | ``` 824 | 825 | ### Monitor system resource utilization for running containers 826 | 827 | To check the CPU, memory, and network I/O usage of a single container, you can use: 828 | 829 | ```sh 830 | docker stats 831 | ``` 832 | 833 | For all containers listed by ID: 834 | 835 | ```sh 836 | docker stats $(docker ps -q) 837 | ``` 838 | 839 | For all containers listed by name: 840 | 841 | ```sh 842 | docker stats $(docker ps --format '{{.Names}}') 843 | ``` 844 | 845 | For all containers listed by image: 846 | 847 | ```sh 848 | docker ps -a -f ancestor=ubuntu 849 | ``` 850 | 851 | Remove all untagged images: 852 | 853 | ```sh 854 | docker rmi $(docker images | grep “^” | awk '{split($0,a," "); print a[3]}') 855 | ``` 856 | 857 | Remove container by a regular expression: 858 | 859 | ```sh 860 | docker ps -a | grep wildfly | awk '{print $1}' | xargs docker rm -f 861 | ``` 862 | 863 | Remove all exited containers: 864 | 865 | ```sh 866 | docker rm -f $(docker ps -a | grep Exit | awk '{ print $1 }') 867 | ``` 868 | 869 | ### Volumes can be files 870 | 871 | Be aware that you can mount files as volumes. For example you can inject a configuration file like this: 872 | 873 | ```sh 874 | # copy file from container 875 | docker run --rm httpd cat /usr/local/apache2/conf/httpd.conf > httpd.conf 876 | 877 | # edit file 878 | vim httpd.conf 879 | 880 | # start container with modified configuration 881 | docker run --rm -it -v "$PWD/httpd.conf:/usr/local/apache2/conf/httpd.conf:ro" -p "80:80" httpd 882 | ``` 883 | 884 | ## Contributing 885 | 886 | Here's how to contribute to this cheat sheet. 887 | 888 | ### Open README.md 889 | 890 | Click [README.md](https://github.com/wsargent/docker-cheat-sheet/blob/master/README.md) <-- this link 891 | 892 | ![Click This](images/click.png) 893 | 894 | ### Edit Page 895 | 896 | ![Edit This](images/edit.png) 897 | 898 | ### Make Changes and Commit 899 | 900 | ![Change This](images/change.png) 901 | 902 | ![Commit](images/commit.png) 903 | -------------------------------------------------------------------------------- /images/change.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wsargent/docker-cheat-sheet/5b1b6d7738d7abf44bdc04eb8c4635359f2f909d/images/change.png -------------------------------------------------------------------------------- /images/click.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wsargent/docker-cheat-sheet/5b1b6d7738d7abf44bdc04eb8c4635359f2f909d/images/click.png -------------------------------------------------------------------------------- /images/commit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wsargent/docker-cheat-sheet/5b1b6d7738d7abf44bdc04eb8c4635359f2f909d/images/commit.png -------------------------------------------------------------------------------- /images/edit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wsargent/docker-cheat-sheet/5b1b6d7738d7abf44bdc04eb8c4635359f2f909d/images/edit.png -------------------------------------------------------------------------------- /pt-br/README.md: -------------------------------------------------------------------------------- 1 | # Docker Cheat Sheet 2 | 3 | **Deseja melhorar este *cheat sheet*? Veja a seção de [Contribuição](#contribution)** 4 | 5 | ## Conteúdo 6 | 7 | * [Porque usar docker](#why-docker) 8 | * [Pré-requisitos](#prerequisites) 9 | * [Instalação](#installation) 10 | * [Containers](#containers) 11 | * [Imagens](#images) 12 | * [Redes](#networks) 13 | * [Registro e Repositório](#registry--repository) 14 | * [Dockerfile](#dockerfile) 15 | * [Camadas](#layers) 16 | * [Links](#links) 17 | * [Volumes](#volumes) 18 | * [Expondo portas](#exposing-ports) 19 | * [Boas práticas](#best-practices) 20 | * [Docker-Compose](#docker-compose) 21 | * [Segurança](#security) 22 | * [Dicas](#tips) 23 | * [Contribuição](#contributing) 24 | 25 | ## Porque usar Docker 26 | 27 | "Com Docker, desenvolvedores podem construir qualquer app em qualquer linguagem usando qualquer conjunto de ferramentas. Apps *Dockerizados* são completamente portáveis e podem rodar em qualquer lugar -- OS X e Windows laptops, servidores QA rodando Ubuntu na nuvem e *data centers* em produção rodando Red Hat em Máquinas Virtuais. 28 | 29 | Desenvolverodes podem iniciar a utilizá-lo rapidamente com um dos mais de 13.000 apps disponíveis no Docker hub. Docker gerencia e rastreia alterações e dependências, tornando mais fácil para *sysadmins* o entendimento do funcionamento de apps construido pelos desenvolvedores. Além disso, com Docker Hub, desenvolvedores podem automatizar o pipeline de *build* e compartilhar *artifacts* com colaboradores através de repositórios públicos ou privados. 30 | 31 | Docker auxilia desenvolvedores a construir e entregar aplicações de alta qualidade de maneira mais rápida." -- [O que é Docker (*What is Docker*)](https://www.docker.com/what-docker#copy1) 32 | 33 | ## Pré-requisitos 34 | 35 | Eu utilizo [Oh My Zsh](https://github.com/ohmyzsh/oh-my-zsh) com [Docker plugin](https://github.com/robbyrussell/oh-my-zsh/wiki/Plugins#docker) para autocompletar os comandos do docker. 36 | 37 | ### Linux 38 | 39 | O kernel 3.10.x é [o requisito mínimo](https://docs.docker.com/engine/installation/binaries/#check-kernel-dependencies) para o uso do Docker. 40 | 41 | ### MacOS 42 | 43 | É necessário *“Mountain Lion”* 10.8 ou mais recente. 44 | 45 | ### Windows 10 46 | 47 | É necessário que o *Hyper-V* esteja habilitado na BIOS. Além disso, para precessadores intel, o VT-D também precisa estar habilidado caso esteja disponível. 48 | 49 | ### Windows Server 50 | 51 | Windows Server 2016 é a versão mínima necessária para instalar o docker e o docker-compose. Existem limitações nessa versão, como por exemplo múltiplas redes virtuais e containers Linux. Windows Server 2019 ou posterior é recomendado. 52 | 53 | ## Instalação 54 | 55 | ### Linux 56 | 57 | Um simples, fácil e rápido *script* é disponibilizado pelo Docker: 58 | 59 | ``` 60 | curl -sSL https://get.docker.com/ | sh 61 | ``` 62 | 63 | Se você não deseja rodar um *shell script* aleatório de internet, basta acessar as [instruções de instalação](https://docs.docker.com/engine/installation/linux/) para a sua distribuição. 64 | 65 | Se você não sabe nada sobre Docker, provavelmente você deveria seguir essa [série de tutoriais](https://docs.docker.com/engine/getstarted/) antes de continuar. 66 | 67 | ### macOS 68 | 69 | Baixe e instale o [*Docker Community Edition*](https://www.docker.com/community-edition). Se você possui o Homebrew-Cask, apenas utilize o comando `brew install --cask docker`. Ou baixe e instale o [*Docker Toolbox*](https://docs.docker.com/toolbox/overview/). [Docker para Mac](https://docs.docker.com/docker-for-mac/) é ok, mas ele ainda não é tão pronto quanto a instalação da VirtualBox. [Veja a comparação](https://docs.docker.com/docker-for-mac/docker-toolbox/). 70 | 71 | > **NOTA** *Docker Toolbox* está no estado *legacy*. Você deveria usar o *Docker Community Edition*. Veja o [*Docker Toolbox*](https://docs.docker.com/toolbox/overview/). 72 | 73 | Assim que você instalar o *Docker Community Edition*, clique no ícone do Docker no *Launchpad*. Em seguida inicie um container: 74 | 75 | ``` 76 | docker run hello-world 77 | ``` 78 | 79 | É isso! Agora você tem um Docker container rodando. 80 | 81 | Se você não sabe nada sobre Docker, provavelmente você deveria seguir essa [série de tutoriais](https://docs.docker.com/engine/getstarted/) antes de continuar. 82 | 83 | ### Windows 10 84 | 85 | Você encontra instruções para instalar o Docker Desktop para Windows [neste link](https://docs.docker.com/desktop/windows/install/). 86 | 87 | Uma vez instalado, abra o *powershell* como administrador 88 | 89 | ```powershell 90 | #Exibe a versão do docker instalado 91 | docker version 92 | 93 | #Todos comandos pull, create, e run 'hello-world' em apenas um: 94 | docker run hello-world 95 | 96 | ``` 97 | 98 | Para continuar as instruções neste *cheat sheet*, clique com botão direito do mouse no ícone do Docker -- no menu iniciar ou onde quer que seja -- e vá em configurações. Para montar volumes, você precisa habilitar o disco C:/ para que as informaçõe sejam transmitidas para os containers (que ainda será explicado neste artigo). 99 | 100 | Para trocar entre containers Windows e Linux, clique com o botão direito no icone do Docker e, na sequência, clique no botão para trocar sistema operacional dos containers. Após fazer isso, todos os containers ques estiveram rodando serão desligados e ficaram inacessíveis até que o SO do container ser trocado novamente. 101 | 102 | 103 | Além disso, se você possui WSL ou WSL2 instalado no seu desktop, você pode instalar o Kernel do Linux para Windows. Instruções para executar tal tarefa podem ser encontradas [aqui] [here](https://techcommunity.microsoft.com/t5/windows-dev-appconsult/using-wsl2-in-a-docker-linux-container-on-windows-to-run-a/ba-p/1482133). Atente-se ao fato de que para isso, é necessário o recurso do Subsistema Windows para Linux. Isso permitirá que os containers sejam acessados pelos sistemas operacionais WSL, bem como o ganho de eficiêcia da execução dos sistemas operacionais WSL no Docker. Por fim, tamém é preferível o uso do [terminal Windows](https://docs.microsoft.com/en-us/windows/terminal/get-started) para tal tarefa. 104 | 105 | ### Windows Server 2016 / 2019 106 | 107 | Siga as instruções da Microsoft disponíveis [aqui](https://docs.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/deploy-containers-on-server#install-docker) 108 | 109 | 110 | Se estiver usando a última versão de 2019, esteja preparado para trabalhar com o *powershell*, uma vez que esta versão não possui interface desktop. Quando inciar a máquina, ela vai logar e ir direto para um janela *powershell*. É recomendado instalar um editor de texto dentre outras ferramentas utilizando [Chocolatey](https://chocolatey.org/install). 111 | 112 | Após a instalação, esses comandos devem funcionar: 113 | 114 | ```powershell 115 | #Exibe a versão do docker instalado 116 | docker version 117 | 118 | #Todos comandos pull, create, e run 'hello-world' em apenas um: 119 | docker run hello-world 120 | 121 | ``` 122 | 123 | O Windows Server 2016 não é capar de rodar images Linux. 124 | 125 | O Windows Server Build 2004 é capar de rodar containers Linux e Windows simultâneamente através do isolamento *Hyper-V*. Quando rodar os containers, utilize o comando ```--isolation=hyperv``` que vai isolar o container utilizando uma instância de kernel separada. 126 | 127 | 128 | ### Checando a versão 129 | 130 | É muito importante que você sempre saiba a versão do Docker que você está utilizando. Isso é muito útil porque você vai saber quais *features* são compatíveis com aquilo que você está rodado. Além disso, isso também é importante pois você saberá quais containers você deve rodar a partir da *Docker store* quando você estiver tentando usar *containers templates*. Sendo assim, vamos dar um olhar em como saber a versão do Docker que você está rodando no momento. 131 | 132 | 133 | * [`docker version`](https://docs.docker.com/engine/reference/commandline/version/): mostra a versão do Docker que você está rodando 134 | 135 | Obtendo a versão do servidor: 136 | 137 | ``` 138 | $ docker version --format '{{.Server.Version}}' 139 | 140 | 1.8.0 141 | ``` 142 | 143 | Você também pode fazer um *dump* dos dados em JSON: 144 | 145 | ``` 146 | $ docker version --format '{{json .}}' 147 | 148 | {"Client":{"Version":"1.8.0","ApiVersion":"1.20","GitCommit":"f5bae0a","GoVersion":"go1.4.2","Os":"linux","Arch":"am"} 149 | ``` 150 | 151 | ## Containers 152 | 153 | [O processo básico isolado do Docker](http://etherealmind.com/basics-docker-containers-hypervisors-coreos/). Containers são para máquinas virtuais o que *threads* são para processos. Ou você pode imaginá-los como *chroots* com esteróides. 154 | 155 | ### Ciclo de vida 156 | 157 | * [`docker create`](https://docs.docker.com/engine/reference/commandline/create) cria um container mas não o inicia. 158 | * [`docker rename`](https://docs.docker.com/engine/reference/commandline/rename/) permite renomear um container. 159 | * [`docker run`](https://docs.docker.com/engine/reference/commandline/run) cria e inicia um container em uma única operação 160 | * [`docker rm`](https://docs.docker.com/engine/reference/commandline/rm) deleta um container 161 | * [`docker update`](https://docs.docker.com/engine/reference/commandline/update/) atualiza os limites de recurso de um container. 162 | 163 | Normalmente, se você rodar um container sem utilizar nenhuma opção ele vai iniciar e parar imediatamente. Se você deseja que ele continue rodando você pode usar o comando `docker run -td `. A opção `-t` vai alocar uma sessão pseudo-TTY e o `-d` vai desacomplar o container automaticamente (ou seja, vai rodar o container em background e imprimir o ID do container). 164 | 165 | Se você deseja um container transiente, `docker run --rm` vai remover o container assim que ele parar. 166 | 167 | Se você deseja mapear um diretório da máquina *host* para o container do Docker, `docker run -v $HOSTDIR:$DOCKERDIR`. Saiba mais em [Volumes](https://github.com/wsargent/docker-cheat-sheet/#volumes). 168 | 169 | Se você também deseja remover o volume associado ao container, ao deletar o container você deve incluir a opção `-v`, por exemplo, `docker rm -v`. 170 | 171 | Também existe o [*logging driver*](https://docs.docker.com/engine/admin/logging/overview/), disponível para containers individuais no docker 1.10. Para rodar o docker com um *log driver* customizado (ou seja, para syslog), use `docker run --log-driver=syslog`. 172 | 173 | Outra opção muito útil é o `docker run --name ` porque você pode especificar o `--name` dentro do comando `run` que vai lhe permite iniciar e parar o container através do nome que você especificou quando o criou. 174 | 175 | 176 | ### Iniciando e parando 177 | 178 | * [`docker start`](https://docs.docker.com/engine/reference/commandline/start) inicia um container, então ele passa a rodar. 179 | * [`docker stop`](https://docs.docker.com/engine/reference/commandline/stop) para um container que esteja rodando. 180 | * [`docker restart`](https://docs.docker.com/engine/reference/commandline/restart) para e inicia um container. 181 | * [`docker pause`](https://docs.docker.com/engine/reference/commandline/pause/) pausa um container que esteja rodando, "congelando" ele da maneira que está. 182 | * [`docker unpause`](https://docs.docker.com/engine/reference/commandline/unpause/) vai despausar um container que estava rodando. 183 | * [`docker wait`](https://docs.docker.com/engine/reference/commandline/wait) bloqueia o container até que ele seja parado. 184 | * [`docker kill`](https://docs.docker.com/engine/reference/commandline/kill) envia um SIGKILL para um container que esteja rodando. 185 | * [`docker attach`](https://docs.docker.com/engine/reference/commandline/attach) vai se conectar a um container que esteja rodando. 186 | 187 | Se você deseja desacoplar um container que esteja rodando, utilize `Ctrl + p, Ctrl + q`. Se você deseja integrar um container com o [gerenciador de processos do host](https://docs.docker.com/engine/admin/host_integration/), inicialize o daemon com `-r=false` e depois use `docker start -a`. 188 | 189 | Se você deseja expor portas do container través do *host*, veja a seção [expondo portas](#exposing-ports). 190 | 191 | Políticas de reinicialização para instâncias "crashadas" do docker são [cobridas aqui](http://container42.com/2014/09/30/docker-restart-policies/). 192 | 193 | #### Restrições de CPU 194 | 195 | Você pode limitar o uso da CPU, seja usando uma porcentagem de todas as CPUs ou usando *cores* específicos. 196 | 197 | Por exemplo, você pode usar a configuração [`cpu-shares`](https://docs.docker.com/engine/reference/run/#/cpu-share-constraint). A configuração é um pouco estranha -- 1024 significa 100% da CPU, então se você quer um container que toma 50% de todos os *cores*, você deve utilizar 512. Veja para mais: 198 | 199 | ``` 200 | docker run -it -c 512 agileek/cpuset-test 201 | ``` 202 | 203 | Você também pode usar alguns *cores* de uma CPU com o comando [`cpuset-cpus`](https://docs.docker.com/engine/reference/run/#/cpuset-constraint). Veja para mais detalhes e alguns vídeos bem legais: 204 | 205 | ``` 206 | docker run -it --cpuset-cpus=0,4,6 agileek/cpuset-test 207 | ``` 208 | 209 | Observe que o Docker ainda pode **enxergar** todas as CPUs de dentro do container -- ele apenas não está usando todas elas. Veja para mais detalhes. 210 | 211 | 212 | #### Restrições de memória 213 | 214 | Você também pode setar [restrições de memória](https://docs.docker.com/engine/reference/run/#/user-memory-constraints) no Docker: 215 | 216 | ``` 217 | docker run -it -m 300M ubuntu:14.04 /bin/bash 218 | ``` 219 | 220 | #### *Capabilities* 221 | 222 | Linux *capabilities* podem ser setadas utilizand as opções `cap-add` e `cap-drop`. Veja See para mais detalhes. Elas devem ser utilizadas para aumentar a seguraça do sistema. 223 | 224 | Para montar um *filesystem* baseado no FUSE, você precisa combinar tanto `--cap-add` quanto `--device`: 225 | 226 | ``` 227 | docker run --rm -it --cap-add SYS_ADMIN --device /dev/fuse sshfs 228 | ``` 229 | 230 | Para dar acesso a um único *device*: 231 | 232 | ``` 233 | docker run -it --device=/dev/ttyUSB0 debian bash 234 | ``` 235 | 236 | Para dar acesso a todos os *devices*: 237 | 238 | ``` 239 | docker run -it --privileged -v /dev/bus/usb:/dev/bus/usb debian bash 240 | ``` 241 | 242 | Para mais informações sobre privilégios em containers [clique aqui](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities). 243 | 244 | ### Info 245 | 246 | * [`docker ps`](https://docs.docker.com/engine/reference/commandline/ps) motra os containers que estão rodando. 247 | * [`docker logs`](https://docs.docker.com/engine/reference/commandline/logs) obtém um log dos containers. (Você pode usar um log customizado, mas eles estão disponíveis apenas para `json-file` e `journald` na versão 1.10). 248 | * [`docker inspect`](https://docs.docker.com/engine/reference/commandline/inspect) olha para todas as informações de um container (incluindo o endereço IP). 249 | * [`docker events`](https://docs.docker.com/engine/reference/commandline/events) obtém os eventos de um container. 250 | * [`docker port`](https://docs.docker.com/engine/reference/commandline/port) mostra a porta pública de um container. 251 | * [`docker top`](https://docs.docker.com/engine/reference/commandline/top) mostra os processos rodando dentro de um container. 252 | * [`docker stats`](https://docs.docker.com/engine/reference/commandline/stats) mostra uma estatística dos recursos que o container está utilizando. 253 | * [`docker diff`](https://docs.docker.com/engine/reference/commandline/diff) mostra os arquivos alterados pelo FS de um container. 254 | 255 | `docker ps -a` mostra os containers que estão rodando e os que foram parados. 256 | 257 | `docker stats --all` mostra uma lista de todos os containers. O padrão é mostrar apenas os que estão rodando. 258 | 259 | ### Importar / Exportar 260 | 261 | * [`docker cp`](https://docs.docker.com/engine/reference/commandline/cp) copia arquivos ou pastas entre o container e o *filesystem* local. 262 | * [`docker export`](https://docs.docker.com/engine/reference/commandline/export) transforma o *filesystem* do container em um fluxo de arquivo *tarball* para STDOUT. 263 | 264 | 265 | ### Executando comandos 266 | 267 | * [`docker exec`](https://docs.docker.com/engine/reference/commandline/exec) executa um comando dentro do container. 268 | 269 | Por exemplo, para entrar em um container fictício, que esteja rodando, chamado foo, inclua um shell a ele da seguinte maneira: `docker exec -it foo /bin/bash`. 270 | 271 | ## Imagens 272 | 273 | Imagens são apenas [templates de um container docker](https://docs.docker.com/engine/understanding-docker/#how-does-a-docker-image-work). 274 | 275 | ### Ciclo de vida 276 | 277 | * [`docker images`](https://docs.docker.com/engine/reference/commandline/images) mostra todas as imagens. 278 | * [`docker import`](https://docs.docker.com/engine/reference/commandline/import) cria uma imagem a partir de um *tarball*. 279 | * [`docker build`](https://docs.docker.com/engine/reference/commandline/build) cria uma imagem a partir de um Dockerfile. 280 | * [`docker commit`](https://docs.docker.com/engine/reference/commandline/commit) cria uma imagem a partir de um container, pausando ele temporariamente caso ele esteja rodando. 281 | * [`docker rmi`](https://docs.docker.com/engine/reference/commandline/rmi) remove uma imagem. 282 | * [`docker load`](https://docs.docker.com/engine/reference/commandline/load) carrega uma imagem a partir de um arquivo tar no STDIN, incluindo imagess and tags (a partir da versão 0.7). 283 | * [`docker save`](https://docs.docker.com/engine/reference/commandline/save) salva uma imagem em um arquivo tar através do STDOUT com todas as camadas pais, tags e versões (a partir do 0.7). 284 | 285 | ### Info 286 | 287 | * [`docker history`](https://docs.docker.com/engine/reference/commandline/history) mostra o histórico de todas as imagens. 288 | * [`docker tag`](https://docs.docker.com/engine/reference/commandline/tag) dar uma tag a uma imagem (local ou *registry*) 289 | 290 | 291 | ### Fazendo uma limpeza 292 | 293 | Você pode utilizar o comando `docker rmi` para remover imagens específicas, porém, existe uma ferramenta chamada [docker-gc](https://github.com/spotify/docker-gc), que de maneira segura, limpa as imagens que não está sendo utilizada por nenhum container. 294 | 295 | that will safely clean up images that are no longer used by any containers. A partir do docker 1.13, o comando `docker image prune` também está disponível para remover imagens que não estão sendo usadas. Veja a seção [Prune](#prune). 296 | 297 | ### Carregar/Salvar imagens 298 | 299 | Carregue uma imagem a partir do arquivo: 300 | ``` 301 | docker load < my_image.tar.gz 302 | ``` 303 | 304 | Salve uma imagem existente usando: 305 | ``` 306 | docker save my_image:my_tag | gzip > my_image.tar.gz 307 | ``` 308 | 309 | ### Importar/Exportar containers 310 | 311 | 312 | Importe um container com uma imagem a partir de um arquivo: 313 | ``` 314 | cat my_container.tar.gz | docker import - my_image:my_tag 315 | ``` 316 | 317 | Exporte um container existente usando: 318 | ``` 319 | docker export my_container | gzip > my_container.tar.gz 320 | ``` 321 | 322 | ### Diferenças entre carregar uma imagem salva e importar um container exportado como uma imagem 323 | 324 | Carregar uma imagem usanfo o comando `load` cria uma nova imagem, incluindo o seu histórico. Importar um container como uma imagem usando o comando `import` cria uma nova imagem excluindo o seu histórico, o que resulta em uma imamgem de tamanho menor do que usando o comando anterior. 325 | 326 | ## Rede 327 | 328 | O Docker possui *features* de [rede](https://docs.docker.com/engine/userguide/networking/). Automaticamente, ele cria 3 interfaces de rede quando você o instala (*bridge*, *host*, *none*). Um novo container é inicializado, por padrão, dentro da rede *bridge*. Para habilitar a comunicação entre multiplos containers, você pode criar uma nova rede e iniciarlizar o mesmo com ela. Isso vai habilitar a comunicação entre os containers dentro dela ao mesmo tempo que os isola dos outros containers que não estejam conectados nesta rede. Além disso, isso permite mapear os nomes dos containers com o seus respectivos endereços IP. Veja [trabalhando com redes](https://docs.docker.com/engine/userguide/networking/work-with-networks/) para mais detalhes. 329 | 330 | ### Ciclo de vida 331 | 332 | * [`docker network create `](https://docs.docker.com/engine/reference/commandline/network_create/) cria uma nova rede (tipo padrão: *bridge*). 333 | * [`docker network rm `](https://docs.docker.com/engine/reference/commandline/network_rm/) remode uma ou mais redes especificadas pelo nome ou identificador. Nenhum container pode se conectar em uma rede quando deletada. 334 | 335 | ### Info 336 | 337 | * [`docker network ls`](https://docs.docker.com/engine/reference/commandline/network_ls/) lista todas as redes. 338 | * [`docker network inspect `](https://docs.docker.com/engine/reference/commandline/network_inspect/) mostra informações detalhadas de uma ou mais redes. 339 | 340 | ### Conexão 341 | 342 | * [`docker network connect `](https://docs.docker.com/engine/reference/commandline/network_connect/) Conecta um container a uma rede 343 | * [`docker network disconnect `](https://docs.docker.com/engine/reference/commandline/network_disconnect/) Desconecta um container de uma rede 344 | 345 | Você pode especificar um [endereço IP para um container](https://blog.jessfraz.com/post/ips-for-all-the-things/): 346 | 347 | ``` 348 | # cria uma nova rede bridge com sua subnet e gateway para seu bloco de endereço IP 349 | docker network create --subnet 203.0.113.0/24 --gateway 203.0.113.254 iptastic 350 | 351 | # roda um container nginx com um IP específico para o dado bloco 352 | $ docker run --rm -it --net iptastic --ip 203.0.113.2 nginx 353 | 354 | # da um culr no IP a partir de qualquer outro local (assumindo que este seja um IP público) 355 | $ curl 203.0.113.2 356 | ``` 357 | 358 | ## Registry & Repositório 359 | 360 | Um repositório é uma coleção *hosteada* de imagens com tagas que juntas criam um sistema de arquivo para um container; 361 | 362 | Um *registry* é um *host* -- ou seja, um servidor que armazena repositórios e disponibiliza um API HTTP para [gerencias o upload e download dos repositórios](https://docs.docker.com/engine/tutorials/dockerrepos/). 363 | 364 | O Docker.com *hostea* seus prórpios [índices](https://hub.docker.com/) em uma central de *registries* qie contém um grande número de repositórios. Sendo assim, essa central [não é muito boa em verificar a procedência das imagens](https://titanous.com/posts/docker-insecurity) e deve ser evitada caso segurança seja algo crítico para você. 365 | 366 | 367 | * [`docker login`](https://docs.docker.com/engine/reference/commandline/login) efetua login em um *registry*. 368 | * [`docker logout`](https://docs.docker.com/engine/reference/commandline/logout) efetua logout de um *registry*. 369 | * [`docker search`](https://docs.docker.com/engine/reference/commandline/search) busca imagens dentro do *registry*. 370 | * [`docker pull`](https://docs.docker.com/engine/reference/commandline/pull) efetua um *pull* de uma imagem do *registry* para sua máquina local. 371 | * [`docker push`](https://docs.docker.com/engine/reference/commandline/push) efetua um *push* de uma imagem para o *registry* a partir da sua máquina local. 372 | 373 | ### Rodando um *registry* local 374 | 375 | Você pode rodar um *registry* local utilizando o projeto de [distribuição docker](https://github.com/docker/distribution) e seguindo as instruções de [*deploy* local](https://github.com/docker/docker.github.io/blob/master/registry/deploying.md). 376 | 377 | Além disso, você pode se interessar pela [lista de emails](https://groups.google.com/a/dockerproject.org/forum/#!forum/distribution). 378 | 379 | ## Dockerfile 380 | 381 | [O arquivo de configuração](https://docs.docker.com/engine/reference/builder/). Prepara um container Docker quando você executa o comando `docker build`. A maioria das pessoas preferem este comando do que o `docker commit`. 382 | 383 | Estes são alguns dos editores de texto que dão suporte, em termos de módulos que destacam a sintaxe, para criar Dockerfiles: 384 | * Se você utiliza o [jEdit](http://jedit.org), eu adicionei um módulo para destacar de sintaxe para o [Dockerfile](https://github.com/wsargent/jedit-docker-mode). Sinta-se livre para usar. 385 | * [Sublime Text 2](https://packagecontrol.io/packages/Dockerfile%20Syntax%20Highlighting) 386 | * [Atom](https://atom.io/packages/language-docker) 387 | * [Vim](https://github.com/ekalinin/Dockerfile.vim) 388 | * [Emacs](https://github.com/spotify/dockerfile-mode) 389 | * [TextMate](https://github.com/docker/docker/tree/master/contrib/syntax/textmate) 390 | * [VS Code](https://github.com/Microsoft/vscode-docker) 391 | * Veja também [Docker meets the IDE](https://domeide.github.io/) 392 | 393 | ### Instruções 394 | 395 | * [.dockerignore](https://docs.docker.com/engine/reference/builder/#dockerignore-file) 396 | * [FROM](https://docs.docker.com/engine/reference/builder/#from) Prepara a imagem base para as instruções subsequentes. 397 | * [MAINTAINER (depreciado - use a tag LABEL)](https://docs.docker.com/engine/reference/builder/#maintainer-deprecated) Define o autor que gerou a imagem. 398 | * [RUN](https://docs.docker.com/engine/reference/builder/#run) executa qualquer comando em uma nova camada em cima de uma imagem e *comita* o resultado. 399 | * [CMD](https://docs.docker.com/engine/reference/builder/#cmd) fornecer padrões para um container em execução. 400 | * [EXPOSE](https://docs.docker.com/engine/reference/builder/#expose) informa o Docker que o container pode escutar uma determinada porta de rede durante o tempo de execução. NOTA: isso não faz com que a porta seja acessível. 401 | * [ENV](https://docs.docker.com/engine/reference/builder/#env) define uma variável de ambiente. 402 | * [ADD](https://docs.docker.com/engine/reference/builder/#add) copia novos arquivos, diretórios, ou arquivos remotos em um container. Invalida cache. Evite usar `ADD` e use o comando `COPY`. 403 | * [COPY](https://docs.docker.com/engine/reference/builder/#copy) copia um novo arquivo ou diretórios para dentro do container. Por padrão copia como root independente das configurações do USER/WORKDIR. Utilize `--chown=:` para poderes de acesso a outros usuários/grupos. (o mesmo é válido para o comando `ADD`.) 404 | * [ENTRYPOINT](https://docs.docker.com/engine/reference/builder/#entrypoint) configura um container que vai rodar como um executável. 405 | * [VOLUME](https://docs.docker.com/engine/reference/builder/#volume) cria um ponto de montagem para montar volumes externos ou outros containers. 406 | * [USER](https://docs.docker.com/engine/reference/builder/#user) define o nome de usuário para os seguintes comandos: RUN / CMD / ENTRYPOINT. 407 | * [WORKDIR](https://docs.docker.com/engine/reference/builder/#workdir) define o diretório de trabalho. 408 | * [ARG](https://docs.docker.com/engine/reference/builder/#arg) define uma variável que existe durante o tempo de execução do *build*. 409 | * [ONBUILD](https://docs.docker.com/engine/reference/builder/#onbuild) adicionar uma instrução alarme que dispara quando a imagem está sendo usada como base para outra *build*. 410 | * [STOPSIGNAL](https://docs.docker.com/engine/reference/builder/#stopsignal) define o sinal de alerta do sistema que vai ser enviado para sair do container. 411 | * [LABEL](https://docs.docker.com/config/labels-custom-metadata/) aplica uma chave/valor para suas imagens, containers, ou *daemons*. 412 | * [SHELL](https://docs.docker.com/engine/reference/builder/#shell) sobrecarrega o shell padrão para rodar os comandos do docker. 413 | * [HEALTHCHECK](https://docs.docker.com/engine/reference/builder/#healthcheck) informa docker como testar o container para testar se tudo está funcionando adequadamente. 414 | 415 | ### Tutorial 416 | 417 | * [Tutorial do Flux7 para o Dockerfile](https://www.flux7.com/tutorial/docker-tutorial-series-part-3-automation-is-the-word-using-dockerfile/) 418 | 419 | ### Exemplos 420 | 421 | * [Exemplos](https://docs.docker.com/engine/reference/builder/#dockerfile-examples) 422 | * [Boas práticas para escrever Dockerfiles](https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/) 423 | * [Michael Crosby](http://crosbymichael.com/) tem mais algumas [boas práticas para criar Dockerfiles](http://crosbymichael.com/dockerfile-best-practices.html) / [parte 2](http://crosbymichael.com/dockerfile-best-practices-take-2.html). 424 | * [Construindo boas imagens Docker](http://jonathan.bergknoff.com/journal/building-good-docker-images) / [Construindo imagens Dockers ainda melhores](http://jonathan.bergknoff.com/journal/building-better-docker-images) 425 | * [Gerenciando a configuração de um container com metadados](https://speakerdeck.com/garethr/managing-container-configuration-with-metadata) 426 | * [Como escrever excelentes Dockerfiles](https://rock-it.pl/how-to-write-excellent-dockerfiles/) 427 | 428 | ## Camadas 429 | 430 | O versionamento dos arquivos de sistema do docker é feito em camadas. Elas funcionam como [comits no git ou *changesets* para arquivos de sistemas](https://docs.docker.com/engine/userguide/storagedriver/imagesandcontainers/). 431 | 432 | ## Links 433 | 434 | Links são como os containers Docker conversam uns com os outros [através de portas TCP/IP](https://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/). [Atlassian](https://blogs.atlassian.com/2013/11/docker-all-the-things-at-atlassian-automation-and-wiring/) mostra alguns exemplos funcionais. Você também pode determinar [links pelo hostname](https://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/#/updating-the-etchosts-file). 435 | 436 | Este está depreciado para estender algumas [redes definidas por usuário](https://docs.docker.com/network/). 437 | 438 | NOTA: se você deseja que os containers comuniquem uns com os outros apenas utilizando links, inicie o do docker daemon com `-icc=false` para desebilitar os processor de intra-comunicação. 439 | 440 | Se você possui um container com nome CONTAINER (especificado por `docker run --name CONTAINER`) e em um Dockerfile, ele possui uma porta exposta: 441 | 442 | ``` 443 | EXPOSE 1337 444 | ``` 445 | 446 | Então, se nós criarmos qualquer outro container chamado LINKED como este: 447 | 448 | ``` 449 | docker run -d --link CONTAINER:ALIAS --name LINKED user/wordpress 450 | ``` 451 | 452 | Então, as portas expostas e os *aliases* do CONTAINER serão mostrados em LINKED com as seguintes variáveis de ambiente: 453 | 454 | ``` 455 | $ALIAS_PORT_1337_TCP_PORT 456 | $ALIAS_PORT_1337_TCP_ADDR 457 | ``` 458 | 459 | Você pode se conectar nele dessa maneira. 460 | 461 | Para deletar os links, utilize o comando `docker rm --link`. 462 | 463 | Geralmente, a *linkagem* entre serviços docker é um subconjunto de um "descobrimento de serviço", um grande problema caso você esteja planejando usar Docker para escalar em produção. Você pode se referir ao livro [The Docker Ecosystem: Service Discovery and Distributed Configuration Stores](https://www.digitalocean.com/community/tutorials/the-docker-ecosystem-service-discovery-and-distributed-configuration-stores) para mais informações. 464 | 465 | ## Volumes 466 | 467 | Os volumes no Docker são [arquivos de sistemas flutuantes](https://docs.docker.com/engine/tutorials/dockervolumes/). Eles não possuem uma conexão particular com um container. Você pode usar volumes montados a partir de [container somente de dados](https://medium.com/@ramangupta/why-docker-data-containers-are-good-589b3c6c749e) para fins de portabilidade. A partir do Docker 1.9.0, o Docker passou a nomear volumes que substituem containers apenas de dados. Considere usar volumes nomeados para implementar isso ao invés de containers de dados. 468 | 469 | ### Ciclo de vidar 470 | 471 | * [`docker volume create`](https://docs.docker.com/engine/reference/commandline/volume_create/) 472 | * [`docker volume rm`](https://docs.docker.com/engine/reference/commandline/volume_rm/) 473 | 474 | ### Informações 475 | 476 | * [`docker volume ls`](https://docs.docker.com/engine/reference/commandline/volume_ls/) 477 | * [`docker volume inspect`](https://docs.docker.com/engine/reference/commandline/volume_inspect/) 478 | 479 | Volumes são úteis em situações em que você não quer usar links (que são apenas TCP/IP). Por exemplo, se você precisar ter duas instancias docker comunicando através de algo deixado no arquivo de sistema. 480 | 481 | Você pode montar vários containers docker de uma vez usando o comando `docker run --volumes-from`. 482 | 483 | Como os volumes são sistemas de arquivos isolados, frequentemente, eles são usados para armazenar estados de alguma computação que é transiente no container. Isto é, você pode ter um container sem estado e transiente continuado de ponto que útimo container deixou. 484 | 485 | Veja [volumes avançados](http://crosbymichael.com/advanced-docker-volumes.html) para mais detalhes. [Container42](http://container42.com/2014/11/03/docker-indepth-volumes/) também é bem útil. 486 | 487 | Você pode [mapear diretórios hosts do MacOS como volumes docker](https://docs.docker.com/engine/tutorials/dockervolumes/#mount-a-host-directory-as-a-data-volume): 488 | 489 | ``` 490 | docker run -v /Users/wsargent/myapp/src:/src 491 | ``` 492 | 493 | Você pode usar columes NFS remotos se você estiver se 494 | You can use remote NFS volumes if you're [sentindo corajoso](https://docs.docker.com/engine/tutorials/dockervolumes/#/mount-a-shared-storage-volume-as-a-data-volume). 495 | 496 | Você também pode considerar rodar containers apenas de dados como descrito [aqui](http://container42.com/2013/12/16/persistent-volumes-with-docker-container-as-volume-pattern/) para obter uma certa portabilidade de dados. 497 | 498 | Saiba que você pode [montar arquivos como volumes](#volumes-can-be-files). 499 | 500 | ## Expondo portas 501 | 502 | 503 | Expor as portas de entrada através do container *host* é [complicado, mas factível](https://docs.docker.com/engine/reference/run/#expose-incoming-ports). 504 | 505 | Isso é feito mapeando a porta do container para com a porta do *host* (apenas usando a interface *localhost*) usando a opção `-p`: 506 | 507 | ``` 508 | docker run -p 127.0.0.1:$HOSTPORT:$CONTAINERPORT --name CONTAINER -t ALGUMA_IMAGEM 509 | ``` 510 | 511 | Você pode informar ao Docker que o container escuta uma porta de rede específica durante a execução ao usar o comando [EXPOSE](https://docs.docker.com/engine/reference/builder/#expose): 512 | 513 | ``` 514 | EXPOSE 515 | ``` 516 | 517 | Note que `EXPOSE` não expões a porta propriamente dita -- apenas a opção `-p` faz isso. Para expor uma porta do container na sua porta *localhost*: 518 | 519 | ``` 520 | iptables -t nat -A DOCKER -p tcp --dport -j DNAT --to-destination : 521 | ``` 522 | 523 | Se você estiver rodando Docker em uma VirtualBox, então você precisa encaminha a porta para lá também usando uma [*forwarded_port*](https://docs.vagrantup.com/v2/networking/forwarded_ports.html). Defina um intervalo de portas que no seu *Vagrantfile* dessa maneira para que vcê possa mapeá-las dinamicamente: 524 | 525 | ``` 526 | Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| 527 | ... 528 | 529 | (49000..49900).each do |port| 530 | config.vm.network :forwarded_port, :host => port, :guest => port 531 | end 532 | 533 | ... 534 | end 535 | ``` 536 | 537 | Se você esquecer o que você mapeou na porta do seu container *host*, utilize `docker port` para mostrar o que você fez: 538 | 539 | ``` 540 | docker port CONTAINER $CONTAINERPORT 541 | ``` 542 | 543 | ## Boas práticas 544 | 545 | É aqui onde boas práticas gerais do Docker uma discusão começa: 546 | 547 | * [A toca do coelho do uso do Docker em testes automatizados](http://gregoryszorc.com/blog/2014/10/16/the-rabbit-hole-of-using-docker-in-automated-tests/) 548 | * [Bridget Kromhout](https://twitter.com/bridgetkromhout) possui um post muito útil no blog: [rodando Docker em produção](http://sysadvent.blogspot.co.uk/2014/12/day-1-docker-in-production-reality-not.html) no Dramafever. 549 | * Também tem o [blog post](http://developers.lyst.com/devops/2014/12/08/docker/) de boas práticas feito pela Lyst. 550 | * [Contruindo um ambiente de desenvolvimento com Docker](https://tersesystems.com/2013/11/20/building-a-development-environment-with-docker/) 551 | * [Discurso em um container Docker](https://samsaffron.com/archive/2013/11/07/discourse-in-a-docker-container) 552 | 553 | ## Docker-Compose 554 | 555 | *Compose* é uma ferramenta para definir e rodar aplicações em vários containers Docker. Com o *compose* você utiliza uma arquivo YAML para configurar os serviços de sua aplicação. Na sequência, com uum único comando, você cria e inicia todos os serviços a partir da sua configuração. Para aprender mais sobre todas as funcionalidades do *Compose*, veja a [lista de funcionalidades](https://docs.docker.com/compose/overview/#features). 556 | 557 | Ao usar este comando, você inicia sua aplicação: 558 | 559 | ``` 560 | docker-compose -f up 561 | ``` 562 | 563 | Você também pode rodar `docker-compose` de maneira desacoplada usando a opção `-d` e parar ele quando quiser utilizando o comando: 564 | 565 | ``` 566 | docker-compose stop 567 | ``` 568 | Você pode desligar tudo 569 | Você pode desligar tudo, remover os containers inteiramente, com o comando `down`. Passe `--volumes` para remover também o dados. 570 | 571 | ## Segurança 572 | 573 | Aqui vão as dicas de segurança do Docker! A página sobre [segurança](https://docs.docker.com/engine/security/security/) do Docker fornece muito mais detalhes. 574 | 575 | Começando do começo: Docker roda como root. Se você está dentro do `docker group`, você [possui acesso root](https://web.archive.org/web/20161226211755/http://reventlov.com/advisories/using-the-docker-command-to-root-the-host). Se você expor um unix socket do docker para um container, você está dando para este container [acesso root para o host](https://www.lvh.io/posts/dont-expose-the-docker-socket-not-even-to-a-container/). 576 | 577 | Docker não pode ser sua única defesa. Você deve protegê-lo da melhor maneira possível. 578 | 579 | Para entender o que os containers deixam exposto, você deveria ler o tutorial [Entendendo e Protegendo Containers Linux](https://www.nccgroup.trust/globalassets/our-research/us/whitepapers/2016/april/ncc_group_understanding_hardening_linux_containers-1-1.pdf) escrito por [Aaron Grattafiori](https://twitter.com/dyn___). Ele um guia completo e compreensível para as questões envolvendo containers com uma grande quantidade de links e notas de rodapés que te leva para conteúdos ainda mais úteis. As dicas de seguranças que vêm a seguir são úteis se você já vem aumentando a segurança dos seus conteiners. Entretanto, elas não substituem o conhecimento sobre o assunto. 580 | 581 | ### Dicas de segurança 582 | 583 | Para a maior segurança possível, é desejável rodar o Docker dentro de uma máquina virtual. Essa dica vem direto do líder do time de segurança do Docker -- [slides](http://www.slideshare.net/jpetazzo/linux-containers-lxc-docker-and-security) / [notas](http://www.projectatomic.io/blog/2014/08/is-it-safe-a-look-at-docker-and-security-from-linuxcon/). 584 | Na sequência, rode ele com AppArmor / seccomp / SELinux / grsec etc para [limitar as permissões do container](http://linux-audit.com/docker-security-best-practices-for-your-vessel-and-containers/). Veja as [funcionalidades de segurança do Docker 1.10](https://blog.docker.com/2016/02/docker-engine-1-10-security/) para mais detalhes. 585 | 586 | As IDs de imagens do Docker são [informações sensíveis](https://medium.com/@quayio/your-docker-image-ids-are-secrets-and-its-time-you-treated-them-that-way-f55e9f14c1a4) e não devem serem expostas para o mundo. Trate elas como *passwords*. 587 | 588 | Veja o [*Cheat Sheet* de segurança do Docker](https://github.com/konstruktoid/Docker/blob/master/Security/CheatSheet.adoc) por [Thomas Sjögren](https://github.com/konstruktoid): tem bastante coisa boa sobre aumentar a segurança em containers lá. 589 | 590 | Dê uma olhada no [script de segurança docker bench](https://github.com/docker/docker-bench-security), baixe os [*white papers*](https://blog.docker.com/2015/05/understanding-docker-security-and-best-practices/). 591 | 592 | Veja as [10 melhores práticas de segurança para imagens Docker](https://snyk.io/blog/10-docker-image-security-best-practices/) do Snyk. 593 | 594 | 595 | Você deve começar usando *kernels* com *patches* estáveis do grsecurity / pax compilados, por exemplo, no [Linux Alpine ](https://en.wikipedia.org/wiki/Alpine_Linux). Se você está usando grsecurity em produção, você deve adquirir o [suporte comercial](https://grsecurity.net/business_support.php) para ter [*patches* estáveis](https://grsecurity.net/announce.php), da mesma forma que você faria para o RedHat. Ele custa $200 por mês, o que pe nada para o seu orçamento de DevOps. 596 | 597 | Desde o Docker 1.11, é fácil limitar o número de processos ativos rodando dentro do container para evitar *fork bombs*. É necessário um kernel Linux >= 4.3 com `CGROUP_PIDS=y` estar na configuração do Kernel. 598 | 599 | ``` 600 | docker run --pids-limit=64 601 | ``` 602 | 603 | Também está disponível, desde a versão 1.11, uma maneira de prevenir que processos ganhem novos privilégios. Essa funcionalidade está no *kernel* Linux desde a versão 3.5. Saiba mais sobre ela neste [post](http://www.projectatomic.io/blog/2016/03/no-new-privs-docker/) blog post. 604 | 605 | ``` 606 | docker run --security-opt=no-new-privileges 607 | ``` 608 | 609 | No [*Chear sheet* de segurança do Docker](http://container-solutions.com/content/uploads/2015/06/15.06.15_DockerCheatSheet_A2.pdf) (está em PDF, o que o torna difícil de usar, então esta copiado na sequência) por [Soluções para containers](http://container-solutions.com/is-docker-safe-for-production/): 610 | 611 | Desligue a comunicação entre processor usando: 612 | 613 | 614 | ``` 615 | docker -d --icc=false --iptables 616 | ``` 617 | 618 | Defina o container como apenas leitura: 619 | 620 | ``` 621 | docker run --read-only 622 | ``` 623 | 624 | Verique as imagens usando `hashsum`: 625 | 626 | ``` 627 | docker pull debian@sha256:a25306f3850e1bd44541976aa7b5fd0a29be 628 | ``` 629 | 630 | Defina os volumes como apenas leitura: 631 | 632 | ``` 633 | docker run -v $(pwd)/secrets:/secrets:ro debian 634 | ``` 635 | 636 | Defina e roda um usuário no seu Dockerfile, assim você não vai rodar como root dentro do container: 637 | 638 | ``` 639 | RUN groupadd -r user && useradd -r -g user user 640 | USER user 641 | ``` 642 | 643 | ### Usando *Namespaces* 644 | 645 | Também temos que trabalha no [*namespaces* do usuário](https://s3hh.wordpress.com/2013/07/19/creating-and-using-containers-without-privilege/) -- ele está na versão 1.1, mas não está disponível por padrão. 646 | 647 | Para habilitar os *namespaces* do usuário no Ubuntu 15.10, [siga o exemplo descrito neste blog](https://raesene.github.io/blog/2016/02/04/Docker-User-Namespaces/). 648 | 649 | ### Vídeos sobre segurança 650 | 651 | * [Usando Docker de maneira segura](https://youtu.be/04LOuMgNj9U) 652 | * [Protegendo suas aplicações usando Docker](https://youtu.be/KmxOXmPhZbk) 653 | * [Segurança do container: eles realmente a tem?](https://youtu.be/a9lE9Urr6AQ) 654 | * [Linux Containers: Futuro ou Fantasia?](https://www.youtube.com/watch?v=iN6QbszB1R8) 655 | 656 | ### Roteiro da Segurança 657 | 658 | O roteiro do Docker fala sobre [suporte ao `secomp`] (https://github.com/docker/docker/blob/master/ROADMAP.md#11-security). Existe também o gerador de política AppArmor chamado [bane](https://github.com/jfrazelle/bane), e eles estão rodando dentro dos [perfis de segurança](https://github.com/docker/docker/issues/17142). 659 | 660 | ## Dicas 661 | 662 | Fontes: 663 | 664 | * [15 dicas do Docjer em 5 minutos](http://sssslide.com/speakerdeck.com/bmorearty/15-docker-tips-in-5-minutes) 665 | * [Docker CodeFresh: hacks para o Docker](https://codefresh.io/blog/everyday-hacks-docker/) 666 | 667 | ### *Prune* 668 | 669 | Os novos [comandos de gerenciamento de dados](https://github.com/docker/docker/pull/26108) chegaram no Docker 1.13: 670 | 671 | * `docker system prune` 672 | * `docker volume prune` 673 | * `docker network prune` 674 | * `docker container prune` 675 | * `docker image prune` 676 | 677 | ### df 678 | 679 | `docker system df` apresenta um resumo do espaço utilizado pelos objetos do Docker. 680 | 681 | ### Heredoc Docker Container 682 | 683 | ``` 684 | docker build -t htop - << EOF 685 | FROM alpine 686 | RUN apk --no-cache add htop 687 | EOF 688 | ``` 689 | 690 | ### Últimos IDs 691 | 692 | ``` 693 | alias dl='docker ps -l -q' 694 | docker run ubuntu echo hello world 695 | docker commit $(dl) helloworld 696 | ``` 697 | 698 | ### Comitar com comandos (precisa de um Dockerfile) 699 | 700 | ``` 701 | docker commit -run='{"Cmd":["postgres", "-too -many -opts"]}' $(dl) postgres 702 | ``` 703 | 704 | ### Obter o endereço IP 705 | 706 | ``` 707 | docker inspect $(dl) | grep -wm1 IPAddress | cut -d '"' -f 4 708 | ``` 709 | 710 | ou com [jq](https://stedolan.github.io/jq/) instalado: 711 | 712 | ``` 713 | docker inspect $(dl) | jq -r '.[0].NetworkSettings.IPAddress' 714 | ``` 715 | 716 | ou usando o [template go](https://docs.docker.com/engine/reference/commandline/inspect): 717 | 718 | ``` 719 | docker inspect -f '{{ .NetworkSettings.IPAddress }}' 720 | ``` 721 | 722 | ou quando *buildando* um imagem com Dockerfile, quando você quiser passar um argumento de build: 723 | 724 | ``` 725 | DOCKER_HOST_IP=`ifconfig | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" | grep -v 127.0.0.1 | awk '{ print $2 }' | cut -f2 -d: | head -n1` 726 | echo DOCKER_HOST_IP = $DOCKER_HOST_IP 727 | docker build \ 728 | --build-arg ARTIFACTORY_ADDRESS=$DOCKER_HOST_IP 729 | -t sometag \ 730 | some-directory/ 731 | ``` 732 | 733 | ### Obter mapeamento de porta 734 | 735 | ``` 736 | docker inspect -f '{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' 737 | ``` 738 | 739 | ### Encontrar container com expressão regular 740 | 741 | ``` 742 | for i in $(docker ps -a | grep "REGEXP_PATTERN" | cut -f1 -d" "); do echo $i; done 743 | ``` 744 | 745 | ### Obter configurações de ambiente 746 | 747 | ``` 748 | docker run --rm ubuntu env 749 | ``` 750 | 751 | ### Matar containers que estão rodando 752 | 753 | ``` 754 | docker kill $(docker ps -q) 755 | ``` 756 | 757 | ### Deletar todos os containers (Forçado!! containers que esteja parados ou rodando) 758 | 759 | ``` 760 | docker rm -f $(docker ps -qa) 761 | ``` 762 | 763 | ### Deletar containers antigos 764 | 765 | ``` 766 | docker ps -a | grep 'weeks ago' | awk '{print $1}' | xargs docker rm 767 | ``` 768 | 769 | ### Deletar containers parados 770 | 771 | ``` 772 | docker rm -v $(docker ps -a -q -f status=exited) 773 | ``` 774 | 775 | ### Deletar containers depois de para-los 776 | 777 | ``` 778 | docker stop $(docker ps -aq) && docker rm -v $(docker ps -aq) 779 | ``` 780 | 781 | ### Deletar imagens pendentes 782 | 783 | ``` 784 | docker rmi $(docker images -q -f dangling=true) 785 | ``` 786 | 787 | ### Delete todas as imagens 788 | 789 | ``` 790 | docker rmi $(docker images -q) 791 | ``` 792 | 793 | ### Deletar volumes pendentes 794 | 795 | As of Docker 1.9: 796 | 797 | ``` 798 | docker volume rm $(docker volume ls -q -f dangling=true) 799 | ``` 800 | 801 | In 1.9.0, the filter `dangling=false` does _not_ work - it is ignored and will list all volumes. 802 | 803 | ### Mostrar dependências das imagens 804 | 805 | ``` 806 | docker images -viz | dot -Tpng -o docker.png 807 | ``` 808 | 809 | ### Reduzingo o tamanho dos containers 810 | 811 | - Limpando APT em uma camada RUN 812 | 813 | Isso deve ser feito na mesma camada dos outros comandos `apt`. Caso contrário, as camadas anteriores irão persistir e as informações originais das suas imagens vão contiuar grandes. 814 | 815 | ``` 816 | RUN {apt commands} \ 817 | && apt-get clean \ 818 | && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* 819 | ``` 820 | 821 | - Achatar uma imagem 822 | ``` 823 | ID=$(docker run -d image-name /bin/bash) 824 | docker export $ID | docker import – flat-image-name 825 | ``` 826 | 827 | - Fazendo backup 828 | ``` 829 | ID=$(docker run -d image-name /bin/bash) 830 | (docker export $ID | gzip -c > image.tgz) 831 | gzip -dc image.tgz | docker import - flat-image-name 832 | ``` 833 | 834 | ### Monitorar os recursos utilizados pelos containers 835 | 836 | Para verificar CPU, memória, ou I/O de rede em um único container, você pode usar: 837 | To check the CPU, memory, and network I/O usage of a single container, you can use: 838 | ``` 839 | docker stats 840 | ``` 841 | 842 | Para todos os containers listados por ID: 843 | ``` 844 | docker stats $(docker ps -q) 845 | ``` 846 | 847 | Para todos os containers listados por nome: 848 | ``` 849 | docker stats $(docker ps --format '{{.Names}}') 850 | ``` 851 | 852 | Para todos os containers listados por imagem: 853 | ``` 854 | docker ps -a -f ancestor=ubuntu 855 | ``` 856 | 857 | Remover todas imagens sem tag: 858 | ``` 859 | docker rmi $(docker images | grep “^” | awk '{split($0,a," "); print a[3]}') 860 | ``` 861 | 862 | Remover um container usando expressão regular: 863 | ``` 864 | docker ps -a | grep wildfly | awk '{print $1}' | xargs docker rm -f 865 | ``` 866 | 867 | Remover todos os containers *exitados*: 868 | ``` 869 | docker rm -f $(docker ps -a | grep Exit | awk '{ print $1 }') 870 | ``` 871 | 872 | ### Volumes podem ser arquivos 873 | 874 | Saiba que você pode montar arquivos como volumes. Por exemplo, se você pode injetar uma configuração dessa forma: 875 | 876 | ``` bash 877 | # copia o arquivo para o container 878 | docker run --rm httpd cat /usr/local/apache2/conf/httpd.conf > httpd.conf 879 | 880 | # edita o arquivo 881 | vim httpd.conf 882 | 883 | # inicia o container com a configuração que foi modificada 884 | docker run --rm -it -v "$PWD/httpd.conf:/usr/local/apache2/conf/httpd.conf:ro" -p "80:80" httpd 885 | ``` 886 | 887 | ## Contrinbuindo com este *chear sheet* 888 | 889 | Aqui está um pequeno tutorial de como contribuir com este documento. 890 | 891 | ### Abra o README.md 892 | 893 | Clique em [README.md](https://github.com/wsargent/docker-cheat-sheet/blob/master/README.md) <-- neste link 894 | 895 | ![Clique aqui](../images/click.png) 896 | 897 | ### Edite a página 898 | 899 | ![Edite aqui](../images/edit.png) 900 | 901 | ### Faça as mudanças e commit elas 902 | 903 | ![Mude aqui](../images/change.png) 904 | 905 | ![Commit](../images/commit.png) 906 | -------------------------------------------------------------------------------- /ru/README.md: -------------------------------------------------------------------------------- 1 | # Docker Cheat Sheet 2 | 3 | **Want to improve this cheat sheet? See the [Contributing](#contributing) section!** 4 | 5 | ## Содержание 6 | 7 | * [Почему Docker](#Почему-Docker) 8 | * [Предпосылки](#Предпосылки) 9 | * [Установка](#Установка) 10 | * [Контейнеры](#Контейнеры) 11 | * [Образы](#Образы) 12 | * [Сеть](#Сеть) 13 | * [Реестр и репозиторий](#registry--repository) 14 | * [Dockerfile](#dockerfile) 15 | * [Слои](#layers) 16 | * [Ссылка](#links) 17 | * [Тома](#volumes) 18 | * [Отображение портов](#exposing-ports) 19 | * [Лучшая практика](#best-practices) 20 | * [Безопасность](#security) 21 | * [Советы](#tips) 22 | * [Содействие](#contributing) 23 | 24 | ## Почему Docker 25 | 26 | "С Docker разработчики могут создавать любое приложение на любом языке, используя любую инструментальную цепочку. Приложения помещаются в контейнер - становятся полностью переносимы и могут работать где угодно - на компьютерах под управлением OS X и Windows, серверах QA, работающих под управлением Ubuntu в облаке, и виртуальных машинах производственного центра обработки данных Red Hat. 27 | 28 | Разработчики могут быстро начать работу, начиная с одного из 13 000 приложений, доступных на Docker Hub. Docker управляет и отслеживает изменения и зависимости, что облегчает для системных администраторов понимание того, как работают приложения, созданные разработчиками. И с Docker Hub разработчики могут автоматизировать свой процес сборки и совместно использовать артефакты с сотрудниками через публичные или частные репозитории. 29 | 30 | Docker помогает разработчикам создавать и отправлять более качественные приложения быстрее " -- [Что такое Docker](https://www.docker.com/what-docker#copy1) 31 | 32 | ## Предпосылки 33 | 34 | Я использую [Oh My Zsh](https://github.com/robbyrussell/oh-my-zsh) вместе с [Docker plugin](https://github.com/robbyrussell/oh-my-zsh/wiki/Plugins#docker) для автозаполнения команд docker. Возможно у вас другой подход. 35 | 36 | ### Linux 37 | 38 | Ядро 3.10.x [минимальное требование](https://docs.docker.com/engine/installation/binaries/#check-kernel-dependencies) для Docker. 39 | 40 | ### MacOS 41 | 42 | 10.8 “Mountain Lion” или более новый. 43 | 44 | ## Установка 45 | 46 | ### Linux 47 | 48 | Быстрый и простой скрипт установки, предоставляемый Docker: 49 | 50 | ``` 51 | curl -sSL https://get.docker.com/ | sh 52 | ``` 53 | 54 | Если вы не хотите запускать случайный сценарий оболочки, см. [Инструкции](https://docs.docker.com/engine/installation/linux/) по установке на ваш дистрибутив. 55 | 56 | Если вы являетесь полноправным новичком Docker, вы должны следовать [сериям учебников](https://docs.docker.com/engine/getstarted/) сейчас. 57 | 58 | ### macOS 59 | Скачать и установить [Docker Community Edition](https://www.docker.com/community-edition). если у вас есть Homebrew-Cask, просто введите `brew install --cask docker`. 60 | Или загрузите и установите [Docker Toolbox](https://docs.docker.com/toolbox/overview/). [Docker для Mac](https://docs.docker.com/docker-for-mac/) это хорошо, но это не совсем так, как установка VirtualBox. [ 61 | См. Сравнение](https://docs.docker.com/docker-for-mac/docker-toolbox/). 62 | 63 | > ** ПРИМЕЧАНИЕ ** Docker Toolbox является устаревшим. вы должны использовать Docker Community Edition, см. (Docker Toolbox)[https://docs.docker.com/toolbox/overview/] 64 | 65 | После установки Docker Community Edition щелкните значок докера. Затем запустите контейнер: 66 | 67 | ``` 68 | docker run hello-world 69 | ``` 70 | 71 | Вот и все, у вас есть работающий контейнер Docker. 72 | 73 | 74 | Если вы являетесь полноправным новичком докеров, вы должны, вероятно, исследовать [серию учебников] (https://docs.docker.com/engine/getstarted/) сейчас. 75 | 76 | ## Контейнеры 77 | 78 | [Ваш основной изолированный процесс Докера](http://etherealmind.com/basics-docker-containers-hypervisors-coreos/). Контейнеры - это виртуальные машины, поскольку потоки относятся к процессам. Или вы можете думать о них как о chroot на стероидах. 79 | 80 | ### Жизненный цикл 81 | 82 | 83 | * [`docker create`](https://docs.docker.com/engine/reference/commandline/create) создает контейнер, но не запускает его. 84 | * [`docker rename`](https://docs.docker.com/engine/reference/commandline/rename/) позволяет переименовать контейнер. 85 | * [`docker run`](https://docs.docker.com/engine/reference/commandline/run) создает и запускает контейнер за одну операцию. 86 | * [`docker rm`](https://docs.docker.com/engine/reference/commandline/rm) удаляет контейнер. 87 | * [`docker update`](https://docs.docker.com/engine/reference/commandline/update/) обновляет ограничения ресурсов контейнера. 88 | 89 | Обычно, если вы запускаете контейнер без параметров, он запускается и останавливается немедленно, если вы хотите его запустить, вы можете использовать команду, `docker run -td container_id` это будет использовать опцию `-t` который будет выделять псевдо-TTY сессию и `-d` который автоматически отсоединяет контейнер (запускает контейнер в фоновом режиме и показыват ID контейнера). 90 | 91 | Если вам нужен переходный контейнер, `docker run --rm` удалит контейнер после его остановки. 92 | 93 | Если вы хотите сопоставить каталог на хосте с контейнером докера, `docker run -v $HOSTDIR:$DOCKERDIR`. Также смотрите [Тома](https://github.com/wsargent/docker-cheat-sheet/#volumes). 94 | 95 | Если вы хотите удалить также тома, связанные с контейнером, удаление контейнера должно включать `-v` измените примерно так `docker rm -v`. 96 | 97 | Существует также [логирование](https://docs.docker.com/engine/admin/logging/overview/) доступны для отдельных контейнеров в докерах 1.10. Чтобы запустить докер с помощью специального лог журнала (например, в syslog), используйте `docker run --log-driver=syslog`. 98 | 99 | Другим полезным вариантом является `docker run --name yourname docker_image` потому что, когда вы укажете `--name` внутри команды run это позволит вам запускать и останавливать контейнер, вызывая его с именем, которое вы указали при его создании. 100 | 101 | ### Запуск и остановка 102 | 103 | * [`docker start`](https://docs.docker.com/engine/reference/commandline/start) запускает контейнер, чтобы он работал. 104 | * [`docker stop`](https://docs.docker.com/engine/reference/commandline/stop) останавливает запущенный контейнер. 105 | * [`docker restart`](https://docs.docker.com/engine/reference/commandline/restart) останавливается и запускает контейнер. 106 | * [`docker pause`](https://docs.docker.com/engine/reference/commandline/pause/) 107 | приостанавливает работу контейнера, "замораживает" его на месте. 108 | * [`docker unpause`](https://docs.docker.com/engine/reference/commandline/unpause/) снимает "заморозку" контейнера. 109 | * [`docker wait`](https://docs.docker.com/engine/reference/commandline/wait) блокирует до остановки контейнера. 110 | * [`docker kill`](https://docs.docker.com/engine/reference/commandline/kill) посылает SIGKILL к запущеннному контейнеру. 111 | * [`docker attach`](https://docs.docker.com/engine/reference/commandline/attach) будет подключаться к работающему контейнеру. 112 | 113 | 114 | Если вы хотите интегрировать контейнер с [диспетчером хостов](https://docs.docker.com/engine/admin/host_integration/), запустите демона с помощью `-r = false`, а затем используйте` docker start -a `. 115 | 116 | Если вы хотите открыть порты контейнера через хост, см. Раздел [раскрытие портов](#открытие-портов). 117 | 118 | Перезагрузка политик в разбитых экземплярах докеров [рассматривается здесь](http://container42.com/2014/09/30/docker-restart-policies/). 119 | 120 | #### Ограничения процессора 121 | 122 | Вы можете ограничить процессор, используя либо процент от всех процессоров, либо используя определенные ядра. 123 | 124 | Например, вы можете указать параметр [`cpu-shares`](https://docs.docker.com/engine/reference/run/#/cpu-share-constraint). Параметр немного странный - 1024 означает 100% CPU, поэтому, если вы хотите, чтобы контейнер занимал 50% всех ядер процессора, вы должны указать 512. См. https://goldmann.pl/blog/2014/09/11/resource-management-in-docker/#_cpu для получения дополнительной информации: 125 | 126 | 127 | ``` 128 | docker run -ti --c 512 agileek/cpuset-test 129 | ``` 130 | Вы также можете использовать только некоторые ядра процессора, используя [`cpuset-cpus`](https://docs.docker.com/engine/reference/run/#/cpuset-constraint). См. https://agileek.github.io/docker/2014/08/06/docker-cpuset/ для получения дополнительной информации: 131 | 132 | 133 | ``` 134 | docker run -ti --cpuset-cpus=0,4,6 agileek/cpuset-test 135 | ``` 136 | Обратите внимание, что Docker все еще может **видеть** все процессоры внутри контейнера -- он просто не использует все из них. Подробнее см. https://github.com/docker/docker/issues/20770. 137 | 138 | 139 | #### Ограничения памяти 140 | 141 | Вы также можете установить [ограничения памяти](https://docs.docker.com/engine/reference/run/#/user-memory-constraints) на Docker: 142 | 143 | ``` 144 | docker run -it -m 300M ubuntu:14.04 /bin/bash 145 | ``` 146 | 147 | #### Возможности 148 | 149 | Возможности Linux можно установить, используя `cap-add` и `cap-drop`. См. https://docs.docker.com/engine/reference/run/#/runtime-privilege-and-linux-capabilities для подробностей. Это должно использоваться для большей безопасности. 150 | 151 | Чтобы подключить файловую систему на основе FUSE, вам необходимо объединить оба --cap-add и --device: 152 | 153 | ``` 154 | docker run --rm -it --cap-add SYS_ADMIN --device /dev/fuse sshfs 155 | ``` 156 | 157 | Обеспечить доступ к одному устройству: 158 | 159 | ``` 160 | docker run -it --device=/dev/ttyUSB0 debian bash 161 | ``` 162 | 163 | Обеспечить доступ ко всем устройствам: 164 | 165 | ``` 166 | docker run -it --privileged -v /dev/bus/usb:/dev/bus/usb debian bash 167 | ``` 168 | 169 | подробнее о привилегированных контейнерах [здесь]( 170 | https://docs.docker.com/engine/reference/run/#/runtime-privilege-and-linux-capabilities) 171 | 172 | 173 | ### Info 174 | 175 | * [`docker ps`](https://docs.docker.com/engine/reference/commandline/ps) показывает запущенные контейнеры. 176 | * [`docker logs`](https://docs.docker.com/engine/reference/commandline/logs) получает журналы из контейнера. (Вы можете использовать собственный драйвер журнала, но журналы доступны только для `json-file` и `journald` в 1.10). 177 | * [`docker inspect`](https://docs.docker.com/engine/reference/commandline/inspect) просматривает всю информацию о контейнере (включая IP-адрес). 178 | * [`docker events`](https://docs.docker.com/engine/reference/commandline/events) получает события из контейнера. 179 | * [`docker port`](https://docs.docker.com/engine/reference/commandline/port) показывает открытый порт контейнера. 180 | * [`docker top`](https://docs.docker.com/engine/reference/commandline/top) показывает запущенные процессы в контейнере. 181 | * [`docker stats`](https://docs.docker.com/engine/reference/commandline/stats) показывает статистику использования ресурсов контейнеров. 182 | * [`docker diff`](https://docs.docker.com/engine/reference/commandline/diff) показывает измененные файлы в FS контейнера. 183 | 184 | `docker ps -a` показывает запущенные и остановленные контейнеры. 185 | 186 | `docker stats --all` показывает текущий список контейнеров. 187 | 188 | ### Импорт / Экспорт 189 | 190 | * [`docker cp`](https://docs.docker.com/engine/reference/commandline/cp) копирует файлы или папки между контейнером и локальной файловой системой. 191 | * [`docker export`](https://docs.docker.com/engine/reference/commandline/export) экспортировать файловую систему контейнера в качестве tar-архива. 192 | 193 | ### Выполнение команд 194 | 195 | * [`docker exec`](https://docs.docker.com/engine/reference/commandline/exec) для выполнения команды в контейнере. 196 | 197 | 198 | Чтобы войти в запущенный контейнер, присоедините новый процесс оболочки к запущенному контейнеру с именем foo, используйте:`docker exec -it foo /bin/bash`. 199 | 200 | ## Образы 201 | 202 | Образы - это просто [шаблоны для docker контейнеров](https://docs.docker.com/engine/understanding-docker/#how-does-a-docker-image-work). 203 | 204 | ### Жизненный цикл 205 | 206 | * [`docker images`](https://docs.docker.com/engine/reference/commandline/images) показывает все образы. 207 | * [`docker import`](https://docs.docker.com/engine/reference/commandline/import) создает образ из архива. 208 | * [`docker build`](https://docs.docker.com/engine/reference/commandline/build) создает образ из Dockerfile. 209 | * [`docker commit`](https://docs.docker.com/engine/reference/commandline/commit) создает образ из контейнера, временно приостанавливая его, если он запущен. 210 | * [`docker rmi`](https://docs.docker.com/engine/reference/commandline/rmi) удаляет образ. 211 | * [`docker load`](https://docs.docker.com/engine/reference/commandline/load) загружает образ из архива tar в качестве STDIN, включая образы и теги (начиная с 0.7). 212 | * [`docker save`](https://docs.docker.com/engine/reference/commandline/save) сохраняет образ в поток архива tar в STDOUT со всеми родительскими слоями, тегами и версиями (начиная с 0,7). 213 | 214 | ### Info 215 | 216 | * [`docker history`](https://docs.docker.com/engine/reference/commandline/history) показывает историю образа. 217 | * [`docker tag`](https://docs.docker.com/engine/reference/commandline/tag) теги образа к имени (локальному или реестру). 218 | 219 | ## Проверка версии Docker 220 | 221 | Очень важно, чтобы вы всегда знали текущую версию Docker, в которой вы сейчас работаете, в любой момент времени. Это очень полезно, потому что вы узнаете, какие функции совместимы с тем, что вы используете. Это также важно, потому что вы знаете, какие контейнеры запускать из хранилища докеров, когда вы пытаетесь получить контейнеры шаблонов. Это говорит о том, как узнать, какая версия докера у нас работает в настоящее время: 222 | 223 | 224 | * ['docker version'](https://docs.docker.com/engine/reference/commandline/version/) проверьте, какая версия докера у вас запущена. 225 | * [docker version [OPTIONS]] 226 | 227 | Получить версию сервера 228 | $ docker version --format '{{.Server.Version}}' 229 | 230 | 1.8.0 231 | Dump raw JSON data 232 | $ docker version --format '{{json .}}' 233 | 234 | {"Client":{"Version":"1.8.0","ApiVersion":"1.20","GitCommit":"f5bae0a","GoVersion":"go1.4.2","Os":"linux","Arch":"am"} 235 | 236 | ### Cleaning up 237 | Хотя вы можете использовать команду `docker rmi` для удаления определенных образов, есть инструмент под названием [docker-gc](https://github.com/spotify/docker-gc), который будет безопасно очищать образы, которые больше не используются любыми контейнерами. 238 | 239 | ### Загрузка/Сохранение образов 240 | 241 | Загрузите образ из файла: 242 | ``` 243 | docker load < my_image.tar.gz 244 | ``` 245 | 246 | Сохранить существующий образ: 247 | ``` 248 | docker save my_image:my_tag | gzip > my_image.tar.gz 249 | ``` 250 | ### Импорт/Экспорт контейнера 251 | 252 | Импортировать контейнер как образ из файла: 253 | ``` 254 | cat my_container.tar.gz | docker import - my_image:my_tag 255 | ``` 256 | 257 | Экспортировать существующий контейнер: 258 | ``` 259 | docker export my_container | gzip > my_container.tar.gz 260 | ``` 261 | 262 | 263 | ### Разница между загрузкой сохраненного образа и импортом экспортированного контейнера в качестве образа 264 | 265 | Загрузка изображения с помощью команды `load` создает новый образ, включая его историю. 266 | Импорт контейнера в качестве образа с помощью команды `import` создает новый образ, исключая историю, которая приводит к меньшему размеру образов по сравнению с загрузкой образа. 267 | 268 | ## Сети 269 | Docker имеет функцию [network](https://docs.docker.com/engine/userguide/networking/). Об этом мало что известно, поэтому это хорошее место для расширения чит-листа. Существует примечание, в котором говорится, что это хороший способ настроить контейнеры докеров, чтобы разговаривать друг с другом без использования портов. Подробнее см. [Работа с сетями](https://docs.docker.com/engine/userguide/networking/work-with-networks/). 270 | 271 | ### Жизненный цикл 272 | 273 | * [`docker network create`](https://docs.docker.com/engine/reference/commandline/network_create/) 274 | * [`docker network rm`](https://docs.docker.com/engine/reference/commandline/network_rm/) 275 | 276 | ### Info 277 | 278 | * [`docker network ls`](https://docs.docker.com/engine/reference/commandline/network_ls/) 279 | * [`docker network inspect`](https://docs.docker.com/engine/reference/commandline/network_inspect/) 280 | 281 | ### Connection 282 | 283 | * [`docker network connect`](https://docs.docker.com/engine/reference/commandline/network_connect/) 284 | * [`docker network disconnect`](https://docs.docker.com/engine/reference/commandline/network_disconnect/) 285 | 286 | Вы можете указать [конкретный IP-адрес для контейнера](https://blog.jessfraz.com/post/ips-for-all-the-things/): 287 | 288 | ``` 289 | # создать новую сеть bridge с вашей подсетью и шлюзом для вашего ip-блока 290 | docker network create --subnet 203.0.113.0/24 --gateway 203.0.113.254 iptastic 291 | 292 | # запустите контейнер nginx с определенным ip в этом блоке 293 | $ docker run --rm -it --net iptastic --ip 203.0.113.2 nginx 294 | 295 | # curl ip из любого другого места (при условии, что это общедоступный ip-блок) 296 | $ curl 203.0.113.2 297 | ``` 298 | 299 | ## Реестр и репозиторий 300 | 301 | Репозиторий - это * размещенная * коллекция помеченных образов, которые вместе создают файловую систему для контейнера. 302 | 303 | Реестр - это * хост * - сервер, который хранит репозитории и предоставляет HTTP API для [управления загрузкой и загрузкой репозиториев](https://docs.docker.com/engine/tutorials/dockerrepos/). 304 | 305 | Docker.com размещает свой собственный [index](https://hub.docker.com/) в центральном реестре, который содержит большое количество репозиториев. Сказав это, центральный реестр докеров (не делает хорошую работу по проверке образов)(https://titanous.com/posts/docker-insecurity), и его следует избегать, если вас беспокоит безопасность. 306 | 307 | * [`docker login`](https://docs.docker.com/engine/reference/commandline/login) для входа в реестр. 308 | * [`docker logout`](https://docs.docker.com/engine/reference/commandline/logout) для выхода из реестра. 309 | * [`docker search`](https://docs.docker.com/engine/reference/commandline/search) ищет реестр для образа. 310 | * [`docker pull`](https://docs.docker.com/engine/reference/commandline/pull) вытаскивает образ из реестра на локальный компьютер. 311 | * [`docker push`](https://docs.docker.com/engine/reference/commandline/push) толкает образ в реестр с локальной машины. 312 | 313 | ### Запуск локального реестра 314 | 315 | Вы можете запустить локальный реестр с помощью проекта [docker distribution](https://github.com/docker/distribution) и посмотреть на [локальное развертывание](https://github.com/docker/docker.github.io/blob/master/registry/deploying.md) инструкци. 316 | 317 | Также см. [Список рассылки](https://groups.google.com/a/dockerproject.org/forum/#!forum/distribution). 318 | 319 | ## Dockerfile 320 | 321 | [Файл конфигурации](https://docs.docker.com/engine/reference/builder/). Устанавливает контейнер Docker, когда вы запускаете на нем `docker build`. Крайне предпочтительнее `docker commit`. 322 | 323 | Вот некоторые распространенные текстовые редакторы и их модули подсветки синтаксиса, которые вы могли бы использовать для создания Dockerfiles: 324 | * Если вы используете [jEdit](http://jedit.org), я установил модуль подсветки синтаксиса для [Dockerfile](https://github.com/wsargent/jedit-docker-mode) вы можете использовать. 325 | * [Sublime Text 2](https://packagecontrol.io/packages/Dockerfile%20Syntax%20Highlighting) 326 | * [Atom](https://atom.io/packages/language-docker) 327 | * [Vim](https://github.com/ekalinin/Dockerfile.vim) 328 | * [Emacs](https://github.com/spotify/dockerfile-mode) 329 | * [TextMate](https://github.com/docker/docker/tree/master/contrib/syntax/textmate) 330 | * [VS Code](https://github.com/Microsoft/vscode-docker) 331 | * Также см. [Docker meets the IDE](https://domeide.github.io/) 332 | 333 | ### Инструкции 334 | 335 | * [.dockerignore](https://docs.docker.com/engine/reference/builder/#dockerignore-file) 336 | * [FROM](https://docs.docker.com/engine/reference/builder/#from) Устанавливает базовое изображение для последующих инструкций. 337 | * [MAINTAINER (устаревший - вместо этого используйте LABEL)](https://docs.docker.com/engine/reference/builder/#maintainer-deprecated) Задайте поле Author созданных образов. 338 | * [RUN](https://docs.docker.com/engine/reference/builder/#run) выполнять любые команды в новом слое поверх текущего образа и фиксировать результаты. 339 | * [CMD](https://docs.docker.com/engine/reference/builder/#cmd) предоставлять значения по умолчанию для исполняемого контейнера. 340 | * [EXPOSE](https://docs.docker.com/engine/reference/builder/#expose) сообщает Docker, что контейнер прослушивает указанные сетевые порты во время выполнения. ПРИМЕЧАНИЕ: на самом деле не делает доступными порты. 341 | * [ENV](https://docs.docker.com/engine/reference/builder/#env) устанавливает переменную среды. 342 | * [ADD](https://docs.docker.com/engine/reference/builder/#add) копирует в контейнер новые файлы, каталоги или удаленный файл. Недействительный кеш. Избегайте `ADD` и вместо этого используйте` COPY`. 343 | * [COPY](https://docs.docker.com/engine/reference/builder/#copy) копирует в контейнер новые файлы или каталоги. Обратите внимание, что это копируется только с правами root, поэтому вы должны вручную управлять вне зависимости от настроек USER / WORKDIR. См. https://github.com/moby/moby/issues/30110 344 | * [ENTRYPOINT](https://docs.docker.com/engine/reference/builder/#entrypoint) настраивает контейнер, который будет запускаться как исполняемый файл. 345 | * [VOLUME](https://docs.docker.com/engine/reference/builder/#volume) создает точку монтирования для внешних томов или других контейнеров. 346 | * [USER](https://docs.docker.com/engine/reference/builder/#user) задает имя пользователя для следующих команд RUN / CMD / ENTRYPOINT. 347 | * [WORKDIR](https://docs.docker.com/engine/reference/builder/#workdir) устанавливает рабочий каталог. 348 | * [ARG](https://docs.docker.com/engine/reference/builder/#arg) определяет переменную времени сборки. 349 | * [ONBUILD](https://docs.docker.com/engine/reference/builder/#onbuild) добавляет инструкцию триггера, когда изображение используется в качестве основы для другой сборки. 350 | * [STOPSIGNAL](https://docs.docker.com/engine/reference/builder/#stopsignal) устанавливает сигнал системного вызова, который будет отправлен в контейнер для выхода. 351 | * [LABEL](https://docs.docker.com/engine/userguide/labels-custom-metadata/) устанавливает сигнал системного вызова, который будет отправлен в контейнер для выхода. 352 | 353 | ### Tutorial 354 | 355 | * [Учебник Flux7's Dockerfile 356 | ](http://flux7.com/blogs/docker/docker-tutorial-series-part-3-automation-is-the-word-using-dockerfile/) 357 | 358 | ### Примеры 359 | 360 | * [Примеры](https://docs.docker.com/engine/reference/builder/#dockerfile-examples) 361 | * [Рекомендации по написанию Dockerfiles](https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/) 362 | * [Michael Crosby](http://crosbymichael.com/) has some more [Dockerfiles best practices](http://crosbymichael.com/dockerfile-best-practices.html) / [take 2](http://crosbymichael.com/dockerfile-best-practices-take-2.html). 363 | * [Building Good Docker Images](http://jonathan.bergknoff.com/journal/building-good-docker-images) / [Создание лучших образов docker](http://jonathan.bergknoff.com/journal/building-better-docker-images) 364 | * [Управление конфигурацией контейнера с метаданными](https://speakerdeck.com/garethr/managing-container-configuration-with-metadata) 365 | * [ Как написать отличный Dockerfiles](https://rock-it.pl/how-to-write-excellent-dockerfiles/) 366 | 367 | ## Слои 368 | 369 | Файловая система с версией в Docker основана на слоях. Они похожи на [git комиты или измекнения для файловой системы](https://docs.docker.com/engine/userguide/storagedriver/imagesandcontainers/). 370 | 371 | ## Связи 372 | Ссылки, как контейнеры Docker общаются друг с другом [через порты TCP/IP](https://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/). [Связь с Redis](https://docs.docker.com/engine/examples/running_redis_service/) и [Atlassian](https://blogs.atlassian.com/2013/11/docker-all-the-things-at-atlassian-automation-and-wiring/) показать приведенные примеры. Вы также можете разрешить [ссылки по имени хоста](https://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/#/updating-the-etchosts-file). 373 | 374 | Это в некоторой степени устарело [сетями определяемыми пользователем](https://docs.docker.com/engine/userguide/networking/#user-defined-networks). 375 | 376 | ПРИМЕЧАНИЕ. Если вы хотите, чтобы контейнеры ТОЛЬКО связывались друг с другом по ссылкам, запустите демон docker с помощью `-icc = false`, чтобы отключить межпроцессное общение. 377 | 378 | Если у вас есть контейнер с именем CONTAINER (указанный `docker run -name CONTAINER`) и в Dockerfile, он имеет открытый порт: 379 | 380 | ``` 381 | EXPOSE 1337 382 | ``` 383 | Тогда, если мы создадим еще один контейнер LINKED, например: 384 | 385 | ``` 386 | docker run -d --link CONTAINER:ALIAS --name LINKED user/wordpress 387 | ``` 388 | Затем открытые порты и псевдонимы CONTAINER будут отображаться в LINKED со следующими переменными среды: 389 | 390 | ``` 391 | $ALIAS_PORT_1337_TCP_PORT 392 | $ALIAS_PORT_1337_TCP_ADDR 393 | ``` 394 | 395 | И вы можете подключиться к нему таким образом. 396 | 397 | Чтобы удалить ссылки, используйте `docker rm --link`. 398 | 399 | Как правило, связи между контейнерами Docker является подмножеством «обнаружения сервисов», что является большой проблемой, если вы планируете использовать Docker в производстве. Пожалуйста, прочитайте [The Docker Ecosystem: Service Discovery and Distributed Configuration Stores](https://www.digitalocean.com/community/tutorials/the-docker-ecosystem-service-discovery-and-distributed-configuration-stores) или большей информации. 400 | 401 | ## Тома 402 | 403 | Тома Docker - [свободно плавающие файловые системы](https://docs.docker.com/engine/tutorials/dockervolumes/).Они не обязательно должны быть подключены к конкретному контейнеру. Вы должны использовать тома, примонированные из [контейнеров только для данных](https://medium.com/@ramangupta/why-docker-data-containers-are-good-589b3c6c749e) для переносимости. 404 | 405 | ### Жизненный цикл 406 | 407 | * [`docker volume create`](https://docs.docker.com/engine/reference/commandline/volume_create/) 408 | * [`docker volume rm`](https://docs.docker.com/engine/reference/commandline/volume_rm/) 409 | 410 | ### Info 411 | 412 | * [`docker volume ls`](https://docs.docker.com/engine/reference/commandline/volume_ls/) 413 | * [`docker volume inspect`](https://docs.docker.com/engine/reference/commandline/volume_inspect/) 414 | 415 | Тома полезны в ситуациях, когда вы не можете использовать ссылки (которые только TCP / IP). Например, если вам нужно, чтобы два экземпляра docker обменивались данными, оставив результат в файловой системе. 416 | 417 | Вы можете смонтировать их в нескольких контейнерах докеров сразу, используя `docker run --volumes-from`. 418 | 419 | Поскольку тома являются изолированными файловыми системами, они часто используются для хранения состояния из вычислений между переходными контейнерами. То есть, у вас может быть контейнер без учета состояния и переходный процесс, запускаемый из скрипта, сдуть его, а затем добавить второй экземпляр переходного контейнера, откуда он остановился. 420 | 421 | 422 | См. [Расширенные тома](http://crosbymichael.com/advanced-docker-volumes.html) для больших подробностей. Container42 is [also helpful](http://container42.com/2014/11/03/docker-indepth-volumes/). 423 | 424 | You can [map MacOS host directories as docker volumes](https://docs.docker.com/engine/tutorials/dockervolumes/#mount-a-host-directory-as-a-data-volume): 425 | 426 | ``` 427 | docker run -v /Users/wsargent/myapp/src:/src 428 | ``` 429 | 430 | You can use remote NFS volumes if you're [feeling brave](https://docs.docker.com/engine/tutorials/dockervolumes/#/mount-a-shared-storage-volume-as-a-data-volume). 431 | 432 | You may also consider running data-only containers as described [here](http://container42.com/2013/12/16/persistent-volumes-with-docker-container-as-volume-pattern/) to provide some data portability. 433 | 434 | [Вы можете [сопоставлять каталоги хостов MacOS в виде докеровских томов]](#volumes-can-be-files) 435 | 436 | 437 | ## Открытие портов 438 | 439 | 440 | Exposing incoming ports through the host container is [fiddly but doable](https://docs.docker.com/engine/reference/run/#expose-incoming-ports). 441 | 442 | This is done by mapping the container port to the host port (only using localhost interface) using `-p`: 443 | 444 | ``` 445 | docker run -p 127.0.0.1:$HOSTPORT:$CONTAINERPORT --name CONTAINER -t someimage 446 | ``` 447 | 448 | You can tell Docker that the container listens on the specified network ports at runtime by using [EXPOSE](https://docs.docker.com/engine/reference/builder/#expose): 449 | 450 | ``` 451 | EXPOSE 452 | ``` 453 | 454 | Note that EXPOSE does not expose the port itself -- only `-p` will do that. To expose the container's port on your localhost's port: 455 | 456 | ``` 457 | iptables -t nat -A DOCKER -p tcp --dport -j DNAT --to-destination : 458 | ``` 459 | 460 | If you're running Docker in Virtualbox, you then need to forward the port there as well, using [forwarded_port](https://docs.vagrantup.com/v2/networking/forwarded_ports.html). Define a range of ports in your Vagrantfile like this so you can dynamically map them: 461 | 462 | ``` 463 | Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| 464 | ... 465 | 466 | (49000..49900).each do |port| 467 | config.vm.network :forwarded_port, :host => port, :guest => port 468 | end 469 | 470 | ... 471 | end 472 | ``` 473 | 474 | If you forget what you mapped the port to on the host container, use `docker port` to show it: 475 | 476 | ``` 477 | docker port CONTAINER $CONTAINERPORT 478 | ``` 479 | 480 | ## Лучша практика 481 | 482 | This is where general Docker best practices and war stories go: 483 | 484 | * [The Rabbit Hole of Using Docker in Automated Tests](http://gregoryszorc.com/blog/2014/10/16/the-rabbit-hole-of-using-docker-in-automated-tests/) 485 | * [Bridget Kromhout](https://twitter.com/bridgetkromhout) has a useful blog post on [running Docker in production](http://sysadvent.blogspot.co.uk/2014/12/day-1-docker-in-production-reality-not.html) at Dramafever. 486 | * There's also a best practices [blog post](http://developers.lyst.com/devops/2014/12/08/docker/) from Lyst. 487 | * [Building a Development Environment With Docker](https://tersesystems.com/2013/11/20/building-a-development-environment-with-docker/) 488 | * [Discourse in a Docker Container](https://samsaffron.com/archive/2013/11/07/discourse-in-a-docker-container) 489 | 490 | ## Безопасность 491 | 492 | This is where security tips about Docker go. The Docker [security](https://docs.docker.com/engine/security/security/) page goes into more detail. 493 | 494 | First things first: Docker runs as root. If you are in the `docker` group, you effectively [have root access](http://reventlov.com/advisories/using-the-docker-command-to-root-the-host). If you expose the docker unix socket to a container, you are giving the container [root access to the host](https://www.lvh.io/posts/dont-expose-the-docker-socket-not-even-to-a-container/). 495 | 496 | Docker should not be your only defense. You should secure and harden it. 497 | 498 | For an understanding of what containers leave exposed, you should read [Understanding and Hardening Linux Containers](https://www.nccgroup.trust/globalassets/our-research/us/whitepapers/2016/april/ncc_group_understanding_hardening_linux_containers-1-1.pdf) by [Aaron Grattafiori](https://twitter.com/dyn___). This is a complete and comprehensive guide to the issues involved with containers, with a plethora of links and footnotes leading on to yet more useful content. The security tips following are useful if you've already hardened containers in the past, but are not a substitute for understanding. 499 | 500 | ### Советы по безопасности 501 | 502 | For greatest security, you want to run Docker inside a virtual machine. This is straight from the Docker Security Team Lead -- [slides](http://www.slideshare.net/jpetazzo/linux-containers-lxc-docker-and-security) / [notes](http://www.projectatomic.io/blog/2014/08/is-it-safe-a-look-at-docker-and-security-from-linuxcon/). Then, run with AppArmor / seccomp / SELinux / grsec etc to [limit the container permissions](http://linux-audit.com/docker-security-best-practices-for-your-vessel-and-containers/). See the [Docker 1.10 security features](https://blog.docker.com/2016/02/docker-engine-1-10-security/) for more details. 503 | 504 | Docker image ids are [sensitive information](https://medium.com/@quayio/your-docker-image-ids-are-secrets-and-its-time-you-treated-them-that-way-f55e9f14c1a4) and should not be exposed to the outside world. Treat them like passwords. 505 | 506 | See the [Docker Security Cheat Sheet](https://github.com/konstruktoid/Docker/blob/master/Security/CheatSheet.adoc) by [Thomas Sjögren](https://github.com/konstruktoid): some good stuff about container hardening in there. 507 | 508 | Check out the [docker bench security script](https://github.com/docker/docker-bench-security), download the [white papers](https://blog.docker.com/2015/05/understanding-docker-security-and-best-practices/) and subscribe to the [mailing lists](https://www.docker.com/docker-security) (unfortunately Docker does not have a unique mailing list, only dev / user). 509 | 510 | You should start off by using a kernel with unstable patches for grsecurity / pax compiled in, such as [Alpine Linux](https://en.wikipedia.org/wiki/Alpine_Linux). If you are using grsecurity in production, you should spring for [commercial support](https://grsecurity.net/business_support.php) for the [stable patches](https://grsecurity.net/announce.php), same as you would do for RedHat. It's $200 a month, which is nothing to your devops budget. 511 | 512 | Since docker 1.11 you can easily limit the number of active processes running inside a container to prevent fork bombs. This requires a linux kernel >= 4.3 with CGROUP_PIDS=y to be in the kernel configuration. 513 | 514 | ``` 515 | docker run --pids-limit=64 516 | ``` 517 | 518 | Also available since docker 1.11 is the ability to prevent processes from gaining new privileges. This feature have been in the linux kernel since version 3.5. You can read more about it in [this](http://www.projectatomic.io/blog/2016/03/no-new-privs-docker/) blog post. 519 | 520 | ``` 521 | docker run --security-opt=no-new-privileges 522 | ``` 523 | 524 | From the [Docker Security Cheat Sheet](http://container-solutions.com/content/uploads/2015/06/15.06.15_DockerCheatSheet_A2.pdf) (it's in PDF which makes it hard to use, so copying below) by [Container Solutions](http://container-solutions.com/is-docker-safe-for-production/): 525 | 526 | Отключите межпроцессное взаимодействие с: 527 | 528 | ``` 529 | docker -d --icc=false --iptables 530 | ``` 531 | 532 | Установите контейнер только для чтения: 533 | 534 | ``` 535 | docker run --read-only 536 | ``` 537 | 538 | Проверьте образы с помощью хэш-функции: 539 | 540 | ``` 541 | docker pull debian@sha256:a25306f3850e1bd44541976aa7b5fd0a29be 542 | ``` 543 | 544 | Установить тома только для чтения: 545 | 546 | ``` 547 | docker run -v $(pwd)/secrets:/secrets:ro debian 548 | ``` 549 | 550 | Определите и запустите пользователя в вашем файле Docker, чтобы вы не запускались как root внутри контейнера: 551 | 552 | ``` 553 | RUN groupadd -r user && useradd -r -g user user 554 | USER user 555 | ``` 556 | 557 | ### User Namespaces 558 | 559 | There's also work on [user namespaces](https://s3hh.wordpress.com/2013/07/19/creating-and-using-containers-without-privilege/) -- it is in 1.10 but is not enabled by default. 560 | 561 | To enable user namespaces ("remap the userns") in Ubuntu 15.10, [follow the blog example](https://raesene.github.io/blog/2016/02/04/Docker-User-Namespaces/). 562 | 563 | ### Security Videos 564 | 565 | * [Using Docker Safely](https://youtu.be/04LOuMgNj9U) 566 | * [Securing your applications using Docker](https://youtu.be/KmxOXmPhZbk) 567 | * [Container security: Do containers actually contain?](https://youtu.be/a9lE9Urr6AQ) 568 | * [Linux Containers: Future or Fantasy?](https://www.youtube.com/watch?v=iN6QbszB1R8) 569 | 570 | ### Security Roadmap 571 | 572 | В дорожной карте docker говорится о [поддержке seccomp]https://github.com/docker/docker/blob/master/ROADMAP.md#11-security). 573 | Существует генератор политики AppArmor, называемый [bane](https://github.com/jfrazelle/bane), и они работают над [профилями безопасности](https://github.com/docker/docker/issues/17142). 574 | 575 | ## Советы 576 | 577 | Источники: 578 | 579 | * [15 Советы docker за 5 минут](http://sssslide.com/speakerdeck.com/bmorearty/15-docker-tips-in-5-minutes) 580 | * [CodeFresh Everyday Hacks Docker](https://codefresh.io/blog/everyday-hacks-docker/) 581 | 582 | ### Prune 583 | 584 | Новые [Команды управления данными](https://github.com/docker/docker/pull/26108) Появились с Docker 1.13: 585 | 586 | * `docker system prune` 587 | * `docker volume prune` 588 | * `docker network prune` 589 | * `docker container prune` 590 | * `docker image prune` 591 | 592 | ### df 593 | 594 | `docker system df` presents a summary of the space currently used by different docker objects. 595 | 596 | ### Контейнер для докеров Heredoc 597 | 598 | ``` 599 | docker build -t htop - << EOF 600 | FROM alpine 601 | RUN apk --no-cache add htop 602 | EOF 603 | ``` 604 | 605 | ### Последние идентификаторы 606 | 607 | ``` 608 | alias dl='docker ps -l -q' 609 | docker run ubuntu echo hello world 610 | docker commit $(dl) helloworld 611 | ``` 612 | 613 | ### Commit с командой (требуется Dockerfile) 614 | 615 | ``` 616 | docker commit -run='{"Cmd":["postgres", "-too -many -opts"]}' $(dl) postgres 617 | ``` 618 | 619 | ### Получить IP-адрес 620 | 621 | ``` 622 | docker inspect $(dl) | grep -wm1 IPAddress | cut -d '"' -f 4 623 | ``` 624 | 625 | или установите [jq](https://stedolan.github.io/jq/): 626 | 627 | ``` 628 | docker inspect $(dl) | jq -r '.[0].NetworkSettings.IPAddress' 629 | ``` 630 | 631 | или используя [go шаблон](https://docs.docker.com/engine/reference/commandline/inspect): 632 | 633 | ``` 634 | docker inspect -f '{{ .NetworkSettings.IPAddress }}' 635 | ``` 636 | 637 | или при создании обрзов из файла Docker, когда вы хотите передать аргумент построения: 638 | 639 | ``` 640 | DOCKER_HOST_IP=`ifconfig | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" | grep -v 127.0.0.1 | awk '{ print $2 }' | cut -f2 -d: | head -n1` 641 | echo DOCKER_HOST_IP = $DOCKER_HOST_IP 642 | docker build \ 643 | --build-arg ARTIFACTORY_ADDRESS=$DOCKER_HOST_IP 644 | -t sometag \ 645 | some-directory/ 646 | ``` 647 | 648 | ### Получить сопоставление портов 649 | 650 | ``` 651 | docker inspect -f '{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' 652 | ``` 653 | 654 | ### Поиск контейнеров путем регулярного выражения 655 | 656 | ``` 657 | for i in $(docker ps -a | grep "REGEXP_PATTERN" | cut -f1 -d" "); do echo $i; done 658 | ``` 659 | 660 | ### Получить настройки среды 661 | 662 | ``` 663 | docker run --rm ubuntu env 664 | ``` 665 | 666 | ### Убить запущенные контейнеры 667 | 668 | ``` 669 | docker kill $(docker ps -q) 670 | ``` 671 | 672 | ### Удалите все контейнеры (принудительные или запущенные контейнеры) 673 | 674 | ``` 675 | docker rm -f $(docker ps -qa) 676 | ``` 677 | 678 | ### Удалить старые контейнеры 679 | 680 | ``` 681 | docker ps -a | grep 'weeks ago' | awk '{print $1}' | xargs docker rm 682 | ``` 683 | 684 | ### Удалить остановленные контейнеры 685 | 686 | ``` 687 | docker rm -v $(docker ps -a -q -f status=exited) 688 | ``` 689 | 690 | ### Удаление контейнеров после остановки 691 | 692 | ``` 693 | docker stop $(docker ps -aq) && docker rm -v $(docker ps -aq) 694 | ``` 695 | 696 | ### Удалить оборванные образы 697 | 698 | ``` 699 | docker rmi $(docker images -q -f dangling=true) 700 | ``` 701 | 702 | ### Удалить все образы 703 | 704 | ``` 705 | docker rmi $(docker images -q) 706 | ``` 707 | 708 | ### Удалить оборванные тома 709 | 710 | Начиная с Docker 1.9: 711 | 712 | ``` 713 | docker volume rm $(docker volume ls -q -f dangling=true) 714 | ``` 715 | 716 | In 1.9.0, the filter `dangling=false` does _not_ work - it is ignored and will list all volumes. 717 | В 1.9.0, фильтр `dangling=false` _не_ работает - он игнорируется и будет перечислять все тома. 718 | 719 | ### Показать зависимости образов 720 | 721 | ``` 722 | docker images -viz | dot -Tpng -o docker.png 723 | ``` 724 | 725 | ### Похудение Docker контейнеров 726 | 727 | - Очистка APT на уровне RUN 728 | 729 | Это должно быть сделано в том же слое, что и другие команды apt. 730 | В противном случае предыдущие слои по-прежнему сохраняют исходную информацию, и ваши образы будут по-прежнему жирными. 731 | 732 | ``` 733 | RUN {apt commands} \ 734 | && apt-get clean \ 735 | && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* 736 | ``` 737 | 738 | - Сгладить образ 739 | ``` 740 | ID=$(docker run -d image-name /bin/bash) 741 | docker export $ID | docker import – flat-image-name 742 | ``` 743 | 744 | - Для резервного копирования 745 | ``` 746 | ID=$(docker run -d image-name /bin/bash) 747 | (docker export $ID | gzip -c > image.tgz) 748 | gzip -dc image.tgz | docker import - flat-image-name 749 | ``` 750 | 751 | ### Мониторинг использования ресурсов системы для запуска контейнеров 752 | 753 | Чтобы проверить использование ЦП, памяти и сетевого ввода-вывода в одном контейнере, вы можете использовать: 754 | 755 | ``` 756 | docker stats 757 | ``` 758 | 759 | Для всех контейнеров, перечисленных в id: 760 | 761 | ``` 762 | docker stats $(docker ps -q) 763 | ``` 764 | 765 | Для всех контейнеров, перечисленных по имени: 766 | 767 | ``` 768 | docker stats $(docker ps --format '{{.Names}}') 769 | ``` 770 | 771 | Для всех контейнеров, перечисленных по образам: 772 | 773 | ``` 774 | docker ps -a -f ancestor=ubuntu 775 | ``` 776 | 777 | Удалить все непомеченные образы 778 | ``` 779 | docker rmi $(docker images | grep “^” | awk '{split($0,a," "); print a[3]}') 780 | ``` 781 | 782 | Удалить контейнер с помощью регулярного выражения 783 | ``` 784 | docker ps -a | grep wildfly | awk '{print $1}' | xargs docker rm -f 785 | ``` 786 | Удалить все завершенные контейнеры 787 | ``` 788 | docker rm -f $(docker ps -a | grep Exit | awk '{ print $1 }') 789 | ``` 790 | 791 | ### Томы могут быть файлами 792 | 793 | Имейте в виду, что вы можете монтировать файлы в виде томов. Например, вы можете ввести файл конфигурации следующим образом: 794 | 795 | ``` bash 796 | # копировать файл из контейнера 797 | docker run --rm httpd cat /usr/local/apache2/conf/httpd.conf > httpd.conf 798 | 799 | # редактировать файл 800 | vim httpd.conf 801 | 802 | # запускать контейнер с измененной конфигурацией 803 | docker run --rm -ti -v "$PWD/httpd.conf:/usr/local/apache2/conf/httpd.conf:ro" -p "80:80" httpd 804 | ``` 805 | 806 | ## Содействие 807 | 808 | Вот как внести свой вклад в этот чит-лист. 809 | 810 | ### Открыть README.md 811 | 812 | Click [README.md](https://github.com/wsargent/docker-cheat-sheet/blob/master/README.md) <-- this link 813 | 814 | ![Click This](../images/click.png) 815 | 816 | ### Отредактировать страницу 817 | 818 | ![Edit This](../images/edit.png) 819 | 820 | ### Внести изменения и зафиксировать 821 | 822 | ![Change This](../images/change.png) 823 | 824 | ![Commit](../images/commit.png) 825 | -------------------------------------------------------------------------------- /zh-cn/README.md: -------------------------------------------------------------------------------- 1 | # Docker Cheat Sheet 2 | 3 | **想要一起来完善这份速查表吗?参见[贡献手册](#贡献手册contributing)部分吧!** 4 | 5 | > 译者注:以下部分链接需科学上网后使用。 6 | > 7 | > Due to GFW, varies links below could not be accessed in China Mainland. 8 | 9 | ## 目录 10 | 11 | * [为何使用 Docker](#为何使用-docker) 12 | * [系统环境(Prerequisites)](#系统环境) 13 | * [安装(Installation)](#安装) 14 | * [容器(Containers)](#容器container) 15 | * [镜像(Images)](#镜像images) 16 | * [网络(Networks)](#网络networks) 17 | * [仓管中心和仓库(Registry & Repository)](#仓管中心和仓库registry--repository) 18 | * [Dockerfile](#dockerfile) 19 | * [层(Layers)](#层layers) 20 | * [链接(Links)](#链接links) 21 | * [卷标(Volumes)](#卷标volumes) 22 | * [暴露端口(Exposing Ports)](#暴露端口exposing-ports) 23 | * [最佳实践(Best Practices)](#最佳实践) 24 | * [安全(security)](#安全security) 25 | * [小贴士(Tips)](#小贴士) 26 | * [贡献手册(Contributing)](#贡献手册contributing) 27 | 28 | ## 为何使用 Docker 29 | 30 | 「通过 Docker,开发者可以使用任何语言任何工具创建任何应用。“Dockerized” 的应用是完全可移植的,能在任何地方运行 - 不管是同事的 OS X 和 Windows 笔记本,或是在云端运行的 Ubuntu QA 服务,还是在虚拟机运行的 Red Hat 产品数据中心。 31 | 32 | Docker Hub 上有 13000+ 的应用,开发者可以从中选取一个进行快速扩展开发。Docker 跟踪管理变更和依赖关系,让系统管理员能更容易理解开发人员是如何让应用运转起来的。而开发者可以通过 Docker Hub 的共有/私有仓库,构建他们的自动化编译,与其他合作者共享成果。 33 | 34 | Docker 帮助开发者更快地构建和发布高质量的应用。」—— [什么是 Docker](https://www.docker.com/what-docker/#copy1) 35 | 36 | ## 系统环境 37 | 38 | 我用的是 [Oh My Zsh](https://github.com/robbyrussell/oh-my-zsh) 和 [Docker 插件](https://github.com/robbyrussell/oh-my-zsh/wiki/Plugins#docker),它可以自动补全 Docker 命令。你的环境可能有所不同。 39 | 40 | ### Linux 41 | 42 | Docker 对于 Linux 内核版本的 [最低要求](https://docs.docker.com/engine/installation/binaries/#check-kernel-dependencies) 为 `3.10.x`。 43 | 44 | ### MacOS 45 | 46 | 10.8「Mountain Lion」或更新版本。 47 | 48 | ### 检查版本 49 | 50 | 时刻关注你当前正在使用的 Docker 版本是十分重要的,这能够帮助你了解可用的特性。同时,可以让你在查找镜像时选择使用的版本。接下来让我们看看如何操作。 51 | 52 | * [`docker version`](https://docs.docker.com/engine/reference/commandline/version/) 查看你正在运行的 Docker 版本。 53 | 54 | 获取 Docker 服务版本: 55 | 56 | ``` 57 | $ docker version --format '{{.Server.Version}}' 58 | 59 | 1.8.0 60 | ``` 61 | 62 | 你也可以输出原始的 JSON 数据: 63 | 64 | ``` 65 | $ docker version --format '{{json .}}' 66 | 67 | {"Client":{"Version":"1.8.0","ApiVersion":"1.20","GitCommit":"f5bae0a","GoVersion":"go1.4.2","Os":"linux","Arch":"am"} 68 | ``` 69 | 70 | ## 安装 71 | 72 | ### Linux 73 | 74 | Docker 官方提供了快速、易用的安装脚本: 75 | 76 | ``` 77 | curl -sSL https://get.docker.com/ | sh 78 | ``` 79 | 80 | 如果你不想执行一个不明不白的 Shell 脚本,那么请看 [安装说明](https://docs.docker.com/engine/installation/linux/),选择你在用的发行版本。 81 | 82 | 如果你是一个 Docker 超新手,那么你应当先去看看 [系列教程](https://docs.docker.com/engine/getstarted/)。 83 | 84 | ### macOS 85 | 86 | 下载并安装 [Docker Community Edition](https://www.docker.com/community-edition)。如果你在使用 Homebrew-Cask,只需在命令行输入 `brew install --cask docker` 即可。下载安装 [Docker Toolbox](https://docs.docker.com/toolbox/overview/) 亦可。[Docker For Mac](https://docs.docker.com/docker-for-mac/) 很赞,但是它的安装过程与 VirtualBox 不太一样。详情请查阅 [比较](https://docs.docker.com/docker-for-mac/docker-toolbox/)。 87 | 88 | > **注意**:Docker Toolbox 已经过时。你应当使用 Docker Community Edition,详见 [Docker Toolbox](https://docs.docker.com/toolbox/overview/) 89 | 90 | 安装好 Docker Community Edition 后,点击 Launchpad 内的 Docker 图标。接着即可启动容器了: 91 | 92 | ``` 93 | docker run hello-world 94 | ``` 95 | 96 | 好了,现在你有了一个运行中的 Docker 容器了。 97 | 98 | ## 容器(Container) 99 | 100 | [关于 Docker 进程隔离的基础](http://etherealmind.com/basics-docker-containers-hypervisors-coreos/)。容器 (Container) 之于虚拟机 (Virtual Machine) 就好比线程之于进程。或者你可以把他们想成是「吃了类固醇的 chroots」。 101 | 102 | ### 生命周期 103 | 104 | * [`docker create`](https://docs.docker.com/engine/reference/commandline/create) 创建容器但不启动它。 105 | * [`docker rename`](https://docs.docker.com/engine/reference/commandline/rename/) 用于重命名容器。 106 | * [`docker run`](https://docs.docker.com/engine/reference/commandline/run) 一键创建并同时启动该容器。 107 | * [`docker rm`](https://docs.docker.com/engine/reference/commandline/rm) 删除容器。 108 | * [`docker update`](https://docs.docker.com/engine/reference/commandline/update/) 调整容器的资源限制。 109 | 110 | 通常情况下,不使用任何命令行选项启动一个容器,该容器将会立即启动并停止。若需保持其运行,你可以使用 `docker run -td container_id` 命令。选项 `-t` 表示分配一个 pseudo-TTY 会话,`-d` 表示自动将容器与终端分离(也就是说在后台运行容器,并输出容器 ID)。 111 | 112 | 如果你需要一个临时容器,可使用 `docker run --rm` 会在容器停止之后删除它。 113 | 114 | 如果你需要映射宿主机 (host) 的目录到 Docker 容器内,可使用 `docker run -v $HOSTDIR:$DOCKERDIR`。详见 [卷标(Volumes)](#卷标volumes) 一节。 115 | 116 | 如果你想同时删除与容器相关联的卷标,那么在删除容器的时候必须包含 `-v` 选项,像这样 `docker rm -v`。 117 | 118 | 从 Docker 1.10 起,其内置一套各容器独立的 [日志引擎](https://docs.docker.com/engine/admin/logging/overview/),每个容器可以独立使用。你可以使用 `docker run --log-driver=syslog` 来自定义日志引擎(例如以上的 `syslog`)。 119 | 120 | ### 启动和停止 121 | 122 | * [`docker start`](https://docs.docker.com/engine/reference/commandline/start) 启动已存在的容器。 123 | * [`docker stop`](https://docs.docker.com/engine/reference/commandline/stop) 停止运行中的容器。 124 | * [`docker restart`](https://docs.docker.com/engine/reference/commandline/restart) 重启容器。 125 | * [`docker pause`](https://docs.docker.com/engine/reference/commandline/pause/) 暂停运行中的容器,将其「冻结」在当前状态。 126 | * [`docker unpause`](https://docs.docker.com/engine/reference/commandline/unpause/) 结束容器暂停状态。 127 | * [`docker wait`](https://docs.docker.com/engine/reference/commandline/wait) 阻塞地等待某个运行中的容器直到停止。 128 | * [`docker kill`](https://docs.docker.com/engine/reference/commandline/kill) 向运行中的容器发送 SIGKILL 指令。 129 | * [`docker attach`](https://docs.docker.com/engine/reference/commandline/attach) 连接到运行中的容器。 130 | 131 | 如果你想将容器的端口 (ports) 暴露至宿主机,请见 [暴露端口](#暴露端口exposing-ports) 一节。 132 | 133 | 关于 Docker 实例崩溃后的重启策略,详见 [本文](http://container42.com/2014/09/30/docker-restart-policies/)。 134 | 135 | #### CPU 限制 136 | 137 | 你可以限制 CPU 资源占用,无论是指定百分比,或是特定核心数。 138 | 139 | 例如,你可以设置 [`cpu-shares`](https://docs.docker.com/engine/reference/run/#/cpu-share-constraint)。该配置看起来有点奇怪 -- 1024 表示 100% CPU,因此如果你希望容器使用所有 CPU 内核的 50%,应将其设置为 512: 140 | 141 | ``` 142 | docker run -ti --c 512 agileek/cpuset-test 143 | ``` 144 | 145 | 更多信息请参阅 。 146 | 147 | 通过 [`cpuset-cpus`](https://docs.docker.com/engine/reference/run/#/cpuset-constraint) 可使用特定 CPU 内核。 148 | 149 | ``` 150 | docker run -ti --cpuset-cpus=0,4,6 agileek/cpuset-test 151 | ``` 152 | 153 | 请参阅 获取更多细节以及一些不错的视频。 154 | 155 | 注意,Docker 在容器内仍然能够 **看到** 全部 CPU -- 它仅仅是不使用全部而已。请参阅 获取更多细节。 156 | 157 | #### 内存限制 158 | 159 | 同样,亦可给 Docker 设置 [内存限制](https://docs.docker.com/engine/reference/run/#/user-memory-constraints): 160 | 161 | ``` 162 | docker run -it -m 300M ubuntu:14.04 /bin/bash 163 | ``` 164 | 165 | #### 能力(Capabilities) 166 | 167 | Linux 的 Capability 可以通过使用 `cap-add` 和 `cap-drop` 设置。请参阅 获取更多细节。这有助于提高安全性。 168 | 169 | 如需要挂载基于 FUSE 的文件系统,你需要结合 `--cap-add` 和 `--device` 使用: 170 | 171 | ``` 172 | docker run --rm -it --cap-add SYS_ADMIN --device /dev/fuse sshfs 173 | ``` 174 | 175 | 授予对某个设备的访问权限: 176 | 177 | ``` 178 | docker run -it --device=/dev/ttyUSB0 debian bash 179 | ``` 180 | 181 | 授予对所有设备的访问权限: 182 | 183 | ``` 184 | docker run -it --privileged -v /dev/bus/usb:/dev/bus/usb debian bash 185 | ``` 186 | 187 | 有关容器特权的更多信息请参阅 [本文](https://docs.docker.com/engine/reference/run/#/runtime-privilege-and-linux-capabilities)。 188 | 189 | ### 信息 190 | 191 | * [`docker ps`](https://docs.docker.com/engine/reference/commandline/ps) 查看运行中的所有容器。 192 | * [`docker logs`](https://docs.docker.com/engine/reference/commandline/logs) 从容器中读取日志。(你也可以使用自定义日志驱动,不过在 1.10 中,它只支持 `json-file` 和 `journald`)。 193 | * [`docker inspect`](https://docs.docker.com/engine/reference/commandline/inspect) 查看某个容器的所有信息(包括 IP 地址)。 194 | * [`docker events`](https://docs.docker.com/engine/reference/commandline/events) 从容器中获取事件 (events)。 195 | * [`docker port`](https://docs.docker.com/engine/reference/commandline/port) 查看容器的公开端口。 196 | * [`docker top`](https://docs.docker.com/engine/reference/commandline/top) 查看容器中活动进程。 197 | * [`docker stats`](https://docs.docker.com/engine/reference/commandline/stats) 查看容器的资源使用量统计信息。 198 | * [`docker diff`](https://docs.docker.com/engine/reference/commandline/diff) 查看容器文件系统中存在改动的文件。 199 | 200 | `docker ps -a` 将显示所有容器,包括运行中和已停止的。 201 | 202 | `docker stats --all` 同样将显示所有容器,默认仅显示运行中的容器。 203 | 204 | ### 导入 / 导出 205 | 206 | * [`docker cp`](https://docs.docker.com/engine/reference/commandline/cp) 在容器和本地文件系统之间复制文件或目录。 207 | * [`docker export`](https://docs.docker.com/engine/reference/commandline/export) 将容器的文件系统打包为归档文件流 (tarball archive stream) 并输出至标准输出 (STDOUT)。 208 | 209 | ### 执行命令 210 | 211 | * [`docker exec`](https://docs.docker.com/engine/reference/commandline/exec) 在容器内执行命令。 212 | 213 | 例如,进入正在运行的 `foo` 容器,并连接 (attach) 到一个新的 Shell 进程:`docker exec -it foo /bin/bash`。 214 | 215 | ## 镜像(Images) 216 | 217 | 镜像是 [Docker 容器的模板](https://docs.docker.com/engine/understanding-docker/#how-does-a-docker-image-work)。 218 | 219 | ### 生命周期 220 | 221 | * [`docker images`](https://docs.docker.com/engine/reference/commandline/images) 查看所有镜像。 222 | * [`docker import`](https://docs.docker.com/engine/reference/commandline/import) 从归档文件创建镜像。 223 | * [`docker build`](https://docs.docker.com/engine/reference/commandline/build) 从 Dockerfile 创建镜像。 224 | * [`docker commit`](https://docs.docker.com/engine/reference/commandline/commit) 为容器创建镜像,如果容器正在运行则会临时暂停。 225 | * [`docker rmi`](https://docs.docker.com/engine/reference/commandline/rmi) 删除镜像。 226 | * [`docker load`](https://docs.docker.com/engine/reference/commandline/load) 从标准输入 (STDIN) 加载归档包 (tar archive) 作为镜像,包括镜像本身和标签 (tags, 0.7 起)。 227 | * [`docker save`](https://docs.docker.com/engine/reference/commandline/save) 将镜像打包为归档包,并输出至标准输出 (STDOUT),包括所有的父层、标签和版本 (parent layers, tags, versions, 0.7 起)。 228 | 229 | ### 其它信息 230 | 231 | * [`docker history`](https://docs.docker.com/engine/reference/commandline/history) 查看镜像的历史记录。 232 | * [`docker tag`](https://docs.docker.com/engine/reference/commandline/tag) 给镜像打标签命名(本地或者仓库均可)。 233 | 234 | ### 清理 235 | 236 | 虽然你可以用 `docker rmi` 命令来删除指定的镜像,不过有个名为 [docker-gc](https://github.com/spotify/docker-gc) 的工具,它可以以一种安全的方式,清理掉那些不再被任何容器使用的镜像。Docker 1.13 起,使用 `docker image prune` 亦可删除未使用的镜像。参见 [清理](#清理)。 237 | 238 | ### 加载 / 保存镜像 239 | 240 | 从文件中加载镜像: 241 | ``` 242 | docker load < my_image.tar.gz 243 | ``` 244 | 245 | 保存既有镜像: 246 | ``` 247 | docker save my_image:my_tag | gzip > my_image.tar.gz 248 | ``` 249 | 250 | ### 导入 / 导出容器 251 | 252 | 从文件中导入容器镜像: 253 | ``` 254 | cat my_container.tar.gz | docker import - my_image:my_tag 255 | ``` 256 | 257 | 导出既有容器: 258 | ``` 259 | docker export my_container | gzip > my_container.tar.gz 260 | ``` 261 | 262 | ### 加载已保存的镜像 与 导入已导出为镜像的容器 的不同 263 | 264 | 通过 `load` 命令来加载镜像,会创建一个新的镜像,并继承原镜像的所有历史。 265 | 通过 `import` 将容器作为镜像导入,也会创建一个新的镜像,但并不包含原镜像的历史,因此会比使用 `load` 方式生成的镜像更小。 266 | 267 | ## 网络(Networks) 268 | 269 | Docker 具备 [网络](https://docs.docker.com/engine/userguide/networking/) 功能。我并不是很了解它,所以这是一个扩展本文的好地方。文档 [使用网络](https://docs.docker.com/engine/userguide/networking/work-with-networks/) 指出,这是一种无需暴露端口即可实现 Docker 容器间通信的好方法。 270 | 271 | ### 生命周期 272 | 273 | * [`docker network create`](https://docs.docker.com/engine/reference/commandline/network_create/) 274 | * [`docker network rm`](https://docs.docker.com/engine/reference/commandline/network_rm/) 275 | 276 | ### 其它信息 277 | 278 | * [`docker network ls`](https://docs.docker.com/engine/reference/commandline/network_ls/) 279 | * [`docker network inspect`](https://docs.docker.com/engine/reference/commandline/network_inspect/) 280 | 281 | ### 建立连接 282 | 283 | * [`docker network connect`](https://docs.docker.com/engine/reference/commandline/network_connect/) 284 | * [`docker network disconnect`](https://docs.docker.com/engine/reference/commandline/network_disconnect/) 285 | 286 | 你可以 [为容器指定 IP 地址](https://blog.jessfraz.com/post/ips-for-all-the-things/): 287 | 288 | ``` 289 | # 使用你自己的子网和网关创建一个桥接网络 290 | docker network create --subnet 203.0.113.0/24 --gateway 203.0.113.254 iptastic 291 | 292 | # 基于以上创建的网络,运行一个 Nginx 容器并指定 IP 293 | $ docker run --rm -it --net iptastic --ip 203.0.113.2 nginx 294 | 295 | # 在其他地方使用 CURL 访问这个 IP(假设该 IP 为公网) 296 | $ curl 203.0.113.2 297 | ``` 298 | 299 | ## 仓管中心和仓库(Registry & Repository) 300 | 301 | 仓库 (repository) 是 *被托管(hosted)* 的已命名镜像 (tagged images) 的集合,这组镜像用于构建容器文件系统。 302 | 303 | 仓管中心 (registry) 则是 *托管服务(host)* -- 用于存储仓库并提供 HTTP API,以便 [管理仓库的上传和下载](https://docs.docker.com/engine/tutorials/dockerrepos/)。 304 | 305 | Docker 官方托管着自己的 [仓管中心](https://hub.docker.com/),包含着数量众多的仓库。不过话虽如此,这个仓管中心 [并没有很好地验证镜像](https://titanous.com/posts/docker-insecurity),所以如果你担心安全问题的话,请尽量避免使用它。 306 | 307 | * [`docker login`](https://docs.docker.com/engine/reference/commandline/login) 登入仓管中心。 308 | * [`docker logout`](https://docs.docker.com/engine/reference/commandline/logout) 登出仓管中心。 309 | * [`docker search`](https://docs.docker.com/engine/reference/commandline/search) 从仓管中心检索镜像。 310 | * [`docker pull`](https://docs.docker.com/engine/reference/commandline/pull) 从仓管中心拉取镜像到本地。 311 | * [`docker push`](https://docs.docker.com/engine/reference/commandline/push) 从本地推送镜像到仓管中心。 312 | 313 | ### 本地仓管中心 314 | 315 | 你可以使用 [docker distribution](https://github.com/docker/distribution) 项目搭建本地的仓管中心,详情参阅 [本地发布 (local deploy)](https://github.com/docker/docker.github.io/blob/master/registry/deploying.md) 的介绍。 316 | 317 | 科学上网后,也可以看看 [Google+ Group](https://groups.google.com/a/dockerproject.org/forum/#!forum/distribution)。 318 | 319 | ## Dockerfile 320 | 321 | 当你执行 `docker build` 时,Docker 将会根据 [配置文件](https://docs.docker.com/engine/reference/builder/) 启动 Docker 容器。远优于使用 `docker commit`。 322 | 323 | 以下是一些编写 Dockerfile 的常用编辑器,并链接到适配的语法高亮模块︰ 324 | 325 | * 如果你在使用 [jEdit](http://jedit.org),你可以使用我开发的 Dockerfile [语法高亮模块](https://github.com/wsargent/jedit-docker-mode)。 326 | * [Sublime Text 2](https://packagecontrol.io/packages/Dockerfile%20Syntax%20Highlighting) 327 | * [Atom](https://atom.io/packages/language-docker) 328 | * [Vim](https://github.com/ekalinin/Dockerfile.vim) 329 | * [Emacs](https://github.com/spotify/dockerfile-mode) 330 | * [TextMate](https://github.com/docker/docker/tree/master/contrib/syntax/textmate) 331 | * 更多信息请参阅 [Docker 遇上 IDE](https://domeide.github.io/) 332 | 333 | ### 指令 334 | 335 | * [.dockerignore](https://docs.docker.com/engine/reference/builder/#dockerignore-file) 336 | * [FROM](https://docs.docker.com/engine/reference/builder/#from) 为其他指令设置基础镜像 (Base Image)。 337 | * [MAINTAINER (deprecated - use LABEL instead)](https://docs.docker.com/engine/reference/builder/#maintainer-deprecated) 为生成的镜像设置作者字段。 338 | * [RUN](https://docs.docker.com/engine/reference/builder/#run) 在当前镜像的基础上生成一个新层并执行命令。 339 | * [CMD](https://docs.docker.com/engine/reference/builder/#cmd) 设置容器默认执行命令。 340 | * [EXPOSE](https://docs.docker.com/engine/reference/builder/#expose) 告知 Docker 容器在运行时所要监听的网络端口。注意:并没有实际上将端口设置为可访问。 341 | * [ENV](https://docs.docker.com/engine/reference/builder/#env) 设置环境变量。 342 | * [ADD](https://docs.docker.com/engine/reference/builder/#add) 将文件、目录或远程文件复制到容器中。缓存无效。请尽量用 `COPY` 代替 `ADD`。 343 | * [COPY](https://docs.docker.com/engine/reference/builder/#copy) 将文件或文件夹复制到容器中。注意:将使用 ROOT 用户复制文件,故无论 USER / WORKDIR 指令如何配置,你都需要手动修改其所有者(`chown`),`ADD` 也是一样。 344 | * [ENTRYPOINT](https://docs.docker.com/engine/reference/builder/#entrypoint) 将容器设为可执行的。 345 | * [VOLUME](https://docs.docker.com/engine/reference/builder/#volume) 在容器内部创建挂载点 (mount point) 指向外部挂载的卷标或其他容器。 346 | * [USER](https://docs.docker.com/engine/reference/builder/#user) 设置随后执行 RUN / CMD / ENTRYPOINT 命令的用户名。 347 | * [WORKDIR](https://docs.docker.com/engine/reference/builder/#workdir) 设置工作目录 (working directory)。 348 | * [ARG](https://docs.docker.com/engine/reference/builder/#arg) 定义编译时 (build-time) 变量。 349 | * [ONBUILD](https://docs.docker.com/engine/reference/builder/#onbuild) 添加触发指令,当该镜像被作为其他镜像的基础镜像时该指令会被触发。 350 | * [STOPSIGNAL](https://docs.docker.com/engine/reference/builder/#stopsignal) 设置停止容器时,向容器内发送的系统调用信号 (system call signal)。 351 | * [LABEL](https://docs.docker.com/config/labels-custom-metadata/) 将键值对元数据 (key/value metadata) 应用到镜像、容器或是守护进程。 352 | 353 | ### 教程 354 | 355 | * [Flux7's Dockerfile Tutorial](http://flux7.com/blogs/docker/docker-tutorial-series-part-3-automation-is-the-word-using-dockerfile/) 356 | 357 | ### 例子 358 | 359 | * [Examples](https://docs.docker.com/engine/reference/builder/#dockerfile-examples) 360 | * [Best practices for writing Dockerfiles](https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/) 361 | * [Michael Crosby](http://crosbymichael.com/) 还有更多的 [Dockerfiles best practices](http://crosbymichael.com/dockerfile-best-practices.html) / [take 2](http://crosbymichael.com/dockerfile-best-practices-take-2.html) 362 | * [Building Good Docker Images](http://jonathan.bergknoff.com/journal/building-good-docker-images) / [Building Better Docker Images](http://jonathan.bergknoff.com/journal/building-better-docker-images) 363 | * [Managing Container Configuration with Metadata](https://speakerdeck.com/garethr/managing-container-configuration-with-metadata) 364 | 365 | ## 层(Layers) 366 | 367 | Docker 的版本化文件系统是基于层的。就像 [Git 的提交或文件变更系统](https://docs.docker.com/engine/userguide/storagedriver/imagesandcontainers/) 一样。 368 | 369 | ## 链接(Links) 370 | 371 | 链接 (links) [通过 TCP/IP 端口](https://docs.docker.com/userguide/dockerlinks/) 实现 Docker 容器之间的通讯。[Atlassian](https://blogs.atlassian.com/2013/11/docker-all-the-things-at-atlassian-automation-and-wiring/) 展示了可用的例子。你还可以 [通过主机名 (hostname) 链接](https://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/#/updating-the-etchosts-file)。 372 | 373 | 在某种意义上来说,该特性已经被 [自定义网络](https://docs.docker.com/network/) 所替代。 374 | 375 | 注意: 如果你希望容器之间**只**通过链接进行通讯,在启动 Docker 守护进程时,请使用 `-icc=false` 来禁用内部进程通讯。 376 | 377 | 假设你有一个名为 CONTAINER 的容器(通过 `docker run --name CONTAINER` 指定)并且在 Dockerfile 中,暴露了一个端口: 378 | 379 | ``` 380 | EXPOSE 1337 381 | ``` 382 | 383 | 然后,我们创建另外一个名为 LINKED 的容器: 384 | 385 | ``` 386 | docker run -d --link CONTAINER:ALIAS --name LINKED user/wordpress 387 | ``` 388 | 389 | 然后 CONTAINER 暴露的端口和别名将会以如下的环境变量出现在 LINKED 中: 390 | 391 | ``` 392 | $ALIAS_PORT_1337_TCP_PORT 393 | $ALIAS_PORT_1337_TCP_ADDR 394 | ``` 395 | 396 | 那么你便可以通过这种方式来连接它了。 397 | 398 | 使用 `docker rm --link` 即可删除链接。 399 | 400 | 通常,Docker 容器(亦可理解为「服务」)之间的链接,是「服务发现」的一个子集。如果你打算在生产中大规模使用 Docker,这将是一个很大的问题。请参阅[The Docker Ecosystem: Service Discovery and Distributed Configuration Stores](https://www.digitalocean.com/community/tutorials/the-docker-ecosystem-service-discovery-and-distributed-configuration-stores) 获取更多信息。 401 | 402 | ## 卷标(Volumes) 403 | 404 | Docker 的卷标 (volumes) 是 [独立的文件系统](https://docs.docker.com/engine/tutorials/dockervolumes/)。它们并非必须连接到特定的容器上。 405 | 406 | ### 生命周期 407 | 408 | * [`docker volume create`](https://docs.docker.com/engine/reference/commandline/volume_create/) 409 | * [`docker volume rm`](https://docs.docker.com/engine/reference/commandline/volume_rm/) 410 | 411 | ### 信息 412 | 413 | * [`docker volume ls`](https://docs.docker.com/engine/reference/commandline/volume_ls/) 414 | * [`docker volume inspect`](https://docs.docker.com/engine/reference/commandline/volume_inspect/) 415 | 416 | 卷标在不能使用链接(只有 TCP/IP)的情况下非常有用。例如,如果你有两个 Docker 实例需要通讯并在文件系统上留下记录。 417 | 418 | 你可以一次性将其挂载到多个 docker 容器上,通过 `docker run --volumes-from`。 419 | 420 | 因为卷标是独立的文件系统,它们通常被用于存储各容器之间的瞬时状态。也就是说,你可以配置一个无状态临时容器,关掉之后,当你有第二个这种临时容器实例的时候,你可以从上一次保存的状态继续执行。 421 | 422 | 查看 [卷标进阶](http://crosbymichael.com/advanced-docker-volumes.html) 来获取更多细节。[Container42](http://container42.com/2014/11/03/docker-indepth-volumes/) 非常有用。 423 | 424 | 你可以 [将宿主 MacOS 的文件夹映射为 Docker 卷标](https://docs.docker.com/engine/tutorials/dockervolumes/#mount-a-host-directory-as-a-data-volume): 425 | 426 | ``` 427 | docker run -v /Users/wsargent/myapp/src:/src 428 | ``` 429 | 430 | 你也可以用远程 NFS 卷标,如果你觉得你 [有足够勇气](https://docs.docker.com/engine/tutorials/dockervolumes/#/mount-a-shared-storage-volume-as-a-data-volume)。 431 | 432 | 还可以考虑运行一个纯数据容器,像 [这里](http://container42.com/2013/12/16/persistent-volumes-with-docker-container-as-volume-pattern/) 所说的那样,提供可移植数据。 433 | 434 | 记得,[文件也可以被挂载为卷标](#将文件挂载为卷标)。 435 | 436 | ## 暴露端口(Exposing ports) 437 | 438 | 通过宿主容器暴露输入端口相当 [繁琐但有效的](https://docs.docker.com/engine/reference/run/#expose-incoming-ports)。 439 | 440 | 例如使用 `-p` 将容器端口映射到宿主端口上(只使用本地主机 (localhost) 接口): 441 | 442 | ``` 443 | docker run -p 127.0.0.1:$HOSTPORT:$CONTAINERPORT --name CONTAINER -t someimage 444 | ``` 445 | 446 | 你可以使用 [EXPOSE](https://docs.docker.com/engine/reference/builder/#expose) 告知 Docker,该容器在运行时监听指定的端口: 447 | 448 | ``` 449 | EXPOSE 450 | ``` 451 | 452 | 但是注意 EXPOSE 并不会直接暴露端口,你需要用参数 `-p` 。比如说你要在 localhost 上暴露容器的端口: 453 | 454 | ``` 455 | iptables -t nat -A DOCKER -p tcp --dport -j DNAT --to-destination : 456 | ``` 457 | 458 | 如果你是在 Virtualbox 中运行 Docker,那么你需要配置端口转发 (forward the port)。使用 [forwarded_port](https://docs.vagrantup.com/v2/networking/forwarded_ports.html) 在 Vagrantfile 上配置暴露的端口范围,这样你就可以动态地映射了: 459 | 460 | ``` 461 | Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| 462 | ... 463 | 464 | (49000..49900).each do |port| 465 | config.vm.network :forwarded_port, :host => port, :guest => port 466 | end 467 | 468 | ... 469 | end 470 | ``` 471 | 472 | 如果你忘记了将什么端口映射到宿主机上的话,可使用 `docker port` 查看: 473 | 474 | ``` 475 | docker port CONTAINER $CONTAINERPORT 476 | ``` 477 | 478 | ## 最佳实践 479 | 480 | 这里有一些最佳实践,以及争论焦点: 481 | 482 | * [The Rabbit Hole of Using Docker in Automated Tests](http://gregoryszorc.com/blog/2014/10/16/the-rabbit-hole-of-using-docker-in-automated-tests/) 483 | * [Bridget Kromhout](https://twitter.com/bridgetkromhout) has a useful blog post on [running Docker in production](http://sysadvent.blogspot.co.uk/2014/12/day-1-docker-in-production-reality-not.html) at Dramafever. 484 | * There's also a best practices [blog post](http://developers.lyst.com/devops/2014/12/08/docker/) from Lyst. 485 | * [A Docker Dev Environment in 24 Hours!](https://engineering.salesforceiq.com/2013/11/05/a-docker-dev-environment-in-24-hours-part-2-of-2.html) 486 | * [Building a Development Environment With Docker](https://tersesystems.com/2013/11/20/building-a-development-environment-with-docker/) 487 | * [Discourse in a Docker Container](https://samsaffron.com/archive/2013/11/07/discourse-in-a-docker-container) 488 | 489 | ## 安全(Security) 490 | 491 | 这节准备讨论一些关于 Docker 安全性的问题。Docker 官方文档 [安全](https://docs.docker.com/articles/security/) 页面讲述了更多细节。 492 | 493 | 首先第一件事:Docker 是有 root 权限的。如果你在 `docker` 组,那么你就有 [root 权限](https://web.archive.org/web/20161226211755/http://reventlov.com/advisories/using-the-docker-command-to-root-the-host)。如果你将 Docker 的 Unix Socket 暴露给容器,意味着你赋予了容器 [宿主机 root 权限](https://www.lvh.io/posts/dont-expose-the-docker-socket-not-even-to-a-container/)。 494 | 495 | Docker 不应当作为唯一的防御措施。你应当使其更加安全可靠。 496 | 497 | 为了更好地理解容器暴露了什么,可参阅由 [Aaron Grattafiori](https://twitter.com/dyn___) 编写的 [Understanding and Hardening Linux Containers](https://www.nccgroup.trust/globalassets/our-research/us/whitepapers/2016/april/ncc_group_understanding_hardening_linux_containers-1-1.pdf)。这是一个完整全面且包含大量链接和脚注的容器问题指南,介绍了许多有用的内容。即使你已经加固过容器,以下的安全提示依然十分有帮助,但并不能代替理解的过程。 498 | 499 | ### 安全提示 500 | 501 | 为了最大的安全性,你应当考虑在虚拟机上运行 Docker。这是直接从 Docker 安全团队拿来的资料 -- [slides](http://www.slideshare.net/jpetazzo/linux-containers-lxc-docker-and-security) / [notes](http://www.projectatomic.io/blog/2014/08/is-it-safe-a-look-at-docker-and-security-from-linuxcon/)。之后,可使用 AppArmor、seccomp、SELinux、grsec 等来 [限制容器的权限](http://linux-audit.com/docker-security-best-practices-for-your-vessel-and-containers/)。更多细节,请查阅 [Docker 1.10 security features](https://blog.docker.com/2016/02/docker-engine-1-10-security/)。 502 | 503 | Docker 镜像 ID 属于 [敏感信息](https://medium.com/@quayio/your-docker-image-ids-are-secrets-and-its-time-you-treated-them-that-way-f55e9f14c1a4) 所以它不应该向外界公开。请将它们当作密码来对待。 504 | 505 | 阅读由 [Thomas Sjögren](https://github.com/konstruktoid) 编写的 [Docker Security Cheat Sheet](https://github.com/konstruktoid/Docker/blob/master/Security/CheatSheet.adoc):关于加固容器的不错的建议。 506 | 507 | 查看 [Docker 安全测试脚本](https://github.com/docker/docker-bench-security),下载 [最佳实践白皮书](https://blog.docker.com/2015/05/understanding-docker-security-and-best-practices/)。 508 | 509 | 你应当远离使用非稳定版本 grsecurity / pax 的内核,比如 [Alpine Linux](https://en.wikipedia.org/wiki/Alpine_Linux)。如果在产品中用了 grsecurity,那么你应该考虑使用有 [商业支持](https://grsecurity.net/business_support.php) 的 [稳定版本](https://grsecurity.net/announce.php),就像你对待 RedHat 那样。虽然要 $200 每月,但对于你的运维预算来说不值一提。 510 | 511 | 从 Docker 1.11 开始,你可以轻松的限制在容器中可用的进程数,以防止 fork 炸弹。 这要求 Linux 内核 >= 4.3,并且要在内核配置中打开 CGROUP_PIDS=y。 512 | 513 | ``` 514 | docker run --pids-limit=64 515 | ``` 516 | 517 | 同时,你也可以限制进程再获取新权限。该功能是 Linux 内核从 3.5 版本开始就拥有的。你可以从 [这篇博客](http://www.projectatomic.io/blog/2016/03/no-new-privs-docker/) 中阅读到更多关于这方面的内容。 518 | 519 | ``` 520 | docker run --security-opt=no-new-privileges 521 | ``` 522 | 523 | 以下内容摘选自 [Container Solutions](http://container-solutions.com/is-docker-safe-for-production/) 的 [Docker Security Cheat Sheet](http://container-solutions.com/content/uploads/2015/06/15.06.15_DockerCheatSheet_A2.pdf)(PDF 版本,难以使用,故复制至此): 524 | 525 | 关闭内部进程通讯: 526 | 527 | ``` 528 | docker -d --icc=false --iptables 529 | ``` 530 | 531 | 设置容器为只读: 532 | 533 | ``` 534 | docker run --read-only 535 | ``` 536 | 537 | 通过 hashsum 来验证卷标: 538 | 539 | ``` 540 | docker pull debian@sha256:a25306f3850e1bd44541976aa7b5fd0a29be 541 | ``` 542 | 543 | 设置卷标为只读: 544 | 545 | ``` 546 | docker run -v $(pwd)/secrets:/secrets:ro debian 547 | ``` 548 | 549 | 在 Dockerfile 中定义用户并以该用户运行,避免在容器中以 ROOT 身份操作: 550 | 551 | ``` 552 | RUN groupadd -r user && useradd -r -g user user 553 | USER user 554 | ``` 555 | 556 | ### 用户命名空间(User Namespaces) 557 | 558 | 还可以通过使用 [用户命名空间](https://s3hh.wordpress.com/2013/07/19/creating-and-using-containers-without-privilege/) -- 自 1.10 版本起已内置,但默认并未启用。 559 | 560 | 要在 Ubuntu 15.10 中启用用户命名空间 (remap the userns),请 [跟着这篇博客的例子](https://raesene.github.io/blog/2016/02/04/Docker-User-Namespaces/) 来做。 561 | 562 | ### 安全相关视频 563 | 564 | * [Using Docker Safely](https://youtu.be/04LOuMgNj9U) 565 | * [Securing your applications using Docker](https://youtu.be/KmxOXmPhZbk) 566 | * [Container security: Do containers actually contain?](https://youtu.be/a9lE9Urr6AQ) 567 | * [Linux Containers: Future or Fantasy?](https://www.youtube.com/watch?v=iN6QbszB1R8) 568 | 569 | ### 安全路线图 570 | 571 | Docker 的路线图提到关于 [seccomp 的支持](https://github.com/docker/docker/blob/master/ROADMAP.md#11-security)。 572 | 一个名为 [bane](https://github.com/jfrazelle/bane) 的 AppArmor 策略生成器正在实现 [安全配置文件](https://github.com/docker/docker/issues/17142)。 573 | 574 | ## 小贴士 575 | 576 | 链接: 577 | 578 | * [15 Docker Tips in 5 minutes](http://sssslide.com/speakerdeck.com/bmorearty/15-docker-tips-in-5-minutes) 579 | * [CodeFresh Everyday Hacks Docker](https://codefresh.io/blog/everyday-hacks-docker/) 580 | 581 | ### 清理 582 | 583 | 最新的 [数据管理命令](https://github.com/docker/docker/pull/26108) 已在 Docker 1.13 实现: 584 | 585 | * `docker system prune` 586 | * `docker volume prune` 587 | * `docker network prune` 588 | * `docker container prune` 589 | * `docker image prune` 590 | 591 | ### df 命令 592 | 593 | `docker system df` 将显示当前 Docker 各部分占用的磁盘空间。 594 | 595 | ### Heredoc 声明 Docker 容器 596 | 597 | ``` 598 | docker build -t htop - << EOF 599 | FROM alpine 600 | RUN apk --no-cache add htop 601 | EOF 602 | ``` 603 | 604 | ### 最近一次的容器 ID 605 | 606 | ``` 607 | alias dl='docker ps -l -q' 608 | docker run ubuntu echo hello world 609 | docker commit $(dl) helloworld 610 | ``` 611 | 612 | ### 带命令的提交(需要 Dockerfile) 613 | 614 | ``` 615 | docker commit -run='{"Cmd":["postgres", "-too -many -opts"]}' $(dl) postgres 616 | ``` 617 | 618 | ### 获取 IP 地址 619 | 620 | ``` 621 | docker inspect $(dl) | grep -wm1 IPAddress | cut -d '"' -f 4 622 | ``` 623 | 624 | 或使用 [jq](https://stedolan.github.io/jq/): 625 | 626 | ``` 627 | docker inspect $(dl) | jq -r '.[0].NetworkSettings.IPAddress' 628 | ``` 629 | 630 | 或使用 [go 模板](https://docs.docker.com/engine/reference/commandline/inspect): 631 | 632 | ``` 633 | docker inspect -f '{{ .NetworkSettings.IPAddress }}' 634 | ``` 635 | 636 | 或在通过 Dockerfile 构建镜像时,通过构建参数 (build argument) 传入: 637 | 638 | ``` 639 | DOCKER_HOST_IP=`ifconfig | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" | grep -v 127.0.0.1 | awk '{ print $2 }' | cut -f2 -d: | head -n1` 640 | echo DOCKER_HOST_IP = $DOCKER_HOST_IP 641 | docker build \ 642 | --build-arg ARTIFACTORY_ADDRESS=$DOCKER_HOST_IP 643 | -t sometag \ 644 | some-directory/ 645 | ``` 646 | 647 | ### 获取端口映射 648 | 649 | ``` 650 | docker inspect -f '{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' 651 | ``` 652 | 653 | ### 通过正则匹配容器 654 | 655 | ``` 656 | for i in $(docker ps -a | grep "REGEXP_PATTERN" | cut -f1 -d" "); do echo $i; done` 657 | ``` 658 | 659 | ### 获取环境变量配置 660 | 661 | ``` 662 | docker run --rm ubuntu env 663 | ``` 664 | 665 | ### 强行终止运行中的容器 666 | 667 | ``` 668 | docker kill $(docker ps -q) 669 | ``` 670 | 671 | ### 删除所有容器(强行删除!无论容器运行或停止) 672 | 673 | ``` 674 | docker rm -f $(docker ps -qa) 675 | ``` 676 | 677 | ### 删除旧容器 678 | 679 | ``` 680 | docker ps -a | grep 'weeks ago' | awk '{print $1}' | xargs docker rm 681 | ``` 682 | 683 | ### 删除已停止的容器 684 | 685 | ``` 686 | docker rm -v `docker ps -a -q -f status=exited` 687 | ``` 688 | 689 | ### 停止并删除容器 690 | 691 | ``` 692 | docker stop $(docker ps -aq) && docker rm -v $(docker ps -aq) 693 | ``` 694 | 695 | ### 删除无用 (dangling) 的镜像 696 | 697 | ``` 698 | docker rmi $(docker images -q -f dangling=true) 699 | ``` 700 | 701 | ### 删除所有镜像 702 | 703 | ``` 704 | docker rmi $(docker images -q) 705 | ``` 706 | 707 | ### 删除无用 (dangling) 的卷标 708 | 709 | Docker 1.9 版本起: 710 | 711 | ``` 712 | docker volume rm $(docker volume ls -q -f dangling=true) 713 | ``` 714 | 715 | 1.9.0 中,参数 `dangling=false` 居然 _没_ 用 - 它会被忽略然后列出所有的卷标。 716 | 717 | ### 查看镜像依赖 718 | 719 | ``` 720 | docker images -viz | dot -Tpng -o docker.png 721 | ``` 722 | 723 | ### Docker 容器瘦身 724 | 725 | - 在某层 (RUN layer) 清理 APT 726 | 727 | 这应当和其他 apt 命令在同一层中完成。 728 | 否则,前面的层将会保持原有信息,而你的镜像则依旧臃肿。 729 | 730 | ``` 731 | RUN {apt commands} \ 732 | && apt-get clean \ 733 | && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* 734 | ``` 735 | 736 | - 压缩镜像 737 | ``` 738 | ID=$(docker run -d image-name /bin/bash) 739 | docker export $ID | docker import – flat-image-name 740 | ``` 741 | 742 | - 备份 743 | ``` 744 | ID=$(docker run -d image-name /bin/bash) 745 | (docker export $ID | gzip -c > image.tgz) 746 | gzip -dc image.tgz | docker import - flat-image-name 747 | ``` 748 | 749 | ### 监视运行中容器的系统资源利用率 750 | 751 | 检查某个容器的 CPU、内存以及网络 I/O 使用情况,你可以: 752 | ``` 753 | docker stats 754 | ``` 755 | 756 | 按 ID 列出所有容器: 757 | ``` 758 | docker stats $(docker ps -q) 759 | ``` 760 | 761 | 按名称列出所有容器: 762 | ``` 763 | docker stats $(docker ps --format '{{.Names}}') 764 | ``` 765 | 766 | 按指定镜像名称列出所有容器: 767 | ``` 768 | docker ps -a -f ancestor=ubuntu 769 | ``` 770 | 771 | 删除所有未标签命名 (untagged) 的容器: 772 | ``` 773 | docker rmi $(docker images | grep “^” | awk '{split($0,a," "); print a[3]}') 774 | ``` 775 | 776 | 通过正则匹配删除指定容器: 777 | ``` 778 | docker ps -a | grep wildfly | awk '{print $1}' | xargs docker rm -f 779 | ``` 780 | 781 | 删除所有已退出 (exited) 的容器: 782 | ``` 783 | docker rm -f $(docker ps -a | grep Exit | awk '{ print $1 }') 784 | ``` 785 | 786 | ### 将文件挂载为卷标 787 | 788 | 文件也可以被挂载为卷标。例如你可以仅仅注入单个配置文件: 789 | 790 | ``` bash 791 | # 从容器复制文件 792 | docker run --rm httpd cat /usr/local/apache2/conf/httpd.conf > httpd.conf 793 | 794 | # 编辑文件 795 | vim httpd.conf 796 | 797 | # 挂载修改后的配置启动容器 798 | docker run --rm -ti -v "$PWD/httpd.conf:/usr/local/apache2/conf/httpd.conf:ro" -p "80:80" httpd 799 | ``` 800 | 801 | ## 贡献手册(Contributing) 802 | 803 | 以下是如何贡献本速查表的说明。 804 | 805 | ### 打开 README.md 806 | 807 | 点击 [README.md](https://github.com/wsargent/docker-cheat-sheet/blob/master/README.md) <-- 这个链接 808 | 809 | ![点击](../images/click.png) 810 | 811 | ### 编辑页面 812 | 813 | ![编辑](../images/edit.png) 814 | 815 | ### 更新并提交 816 | 817 | ![修改](../images/change.png) 818 | 819 | ![提交](../images/commit.png) 820 | --------------------------------------------------------------------------------