github.com/jiasir/docker@v1.3.3-0.20170609024000-252e610103e7/docs/reference/commandline/service_create.md (about)

     1  ---
     2  title: "service create"
     3  description: "The service create command description and usage"
     4  keywords: "service, create"
     5  ---
     6  
     7  <!-- This file is maintained within the docker/docker Github
     8       repository at https://github.com/docker/docker/. Make all
     9       pull requests against that repo. If you see this file in
    10       another repository, consider it read-only there, as it will
    11       periodically be overwritten by the definitive file. Pull
    12       requests which include edits to this file in other repositories
    13       will be rejected.
    14  -->
    15  
    16  # service create
    17  
    18  ```Markdown
    19  Usage:  docker service create [OPTIONS] IMAGE [COMMAND] [ARG...]
    20  
    21  Create a new service
    22  
    23  Options:
    24        --constraint list                    Placement constraints
    25        --container-label list               Container labels
    26    -d, --detach                             Exit immediately instead of waiting for the service to converge (default true)
    27        --dns list                           Set custom DNS servers
    28        --dns-option list                    Set DNS options
    29        --dns-search list                    Set custom DNS search domains
    30        --endpoint-mode string               Endpoint mode (vip or dnsrr) (default "vip")
    31        --entrypoint command                 Overwrite the default ENTRYPOINT of the image
    32    -e, --env list                           Set environment variables
    33        --env-file list                      Read in a file of environment variables
    34        --group list                         Set one or more supplementary user groups for the container
    35        --health-cmd string                  Command to run to check health
    36        --health-interval duration           Time between running the check (ms|s|m|h)
    37        --health-retries int                 Consecutive failures needed to report unhealthy
    38        --health-start-period duration       Start period for the container to initialize before counting retries towards unstable (ms|s|m|h)
    39        --health-timeout duration            Maximum time to allow one check to run (ms|s|m|h)
    40        --help                               Print usage
    41        --host list                          Set one or more custom host-to-IP mappings (host:ip)
    42        --hostname string                    Container hostname
    43    -l, --label list                         Service labels
    44        --limit-cpu decimal                  Limit CPUs
    45        --limit-memory bytes                 Limit Memory
    46        --log-driver string                  Logging driver for service
    47        --log-opt list                       Logging driver options
    48        --mode string                        Service mode (replicated or global) (default "replicated")
    49        --mount mount                        Attach a filesystem mount to the service
    50        --name string                        Service name
    51        --network list                       Network attachments
    52        --no-healthcheck                     Disable any container-specified HEALTHCHECK
    53        --placement-pref pref                Add a placement preference
    54    -p, --publish port                       Publish a port as a node port
    55    -q, --quiet                              Suppress progress output
    56        --read-only                          Mount the container's root filesystem as read only
    57        --replicas uint                      Number of tasks
    58        --reserve-cpu decimal                Reserve CPUs
    59        --reserve-memory bytes               Reserve Memory
    60        --restart-condition string           Restart when condition is met ("none"|"on-failure"|"any") (default "any")
    61        --restart-delay duration             Delay between restart attempts (ns|us|ms|s|m|h) (default 5s)
    62        --restart-max-attempts uint          Maximum number of restarts before giving up
    63        --restart-window duration            Window used to evaluate the restart policy (ns|us|ms|s|m|h)
    64        --rollback-delay duration            Delay between task rollbacks (ns|us|ms|s|m|h) (default 0s)
    65        --rollback-failure-action string     Action on rollback failure ("pause"|"continue") (default "pause")
    66        --rollback-max-failure-ratio float   Failure rate to tolerate during a rollback (default 0)
    67        --rollback-monitor duration          Duration after each task rollback to monitor for failure (ns|us|ms|s|m|h) (default 5s)
    68        --rollback-order string              Rollback order ("start-first"|"stop-first") (default "stop-first")
    69        --rollback-parallelism uint          Maximum number of tasks rolled back simultaneously (0 to roll back all at once) (default 1)
    70        --secret secret                      Specify secrets to expose to the service
    71        --stop-grace-period duration         Time to wait before force killing a container (ns|us|ms|s|m|h) (default 10s)
    72        --stop-signal string                 Signal to stop the container
    73    -t, --tty                                Allocate a pseudo-TTY
    74        --update-delay duration              Delay between updates (ns|us|ms|s|m|h) (default 0s)
    75        --update-failure-action string       Action on update failure ("pause"|"continue"|"rollback") (default "pause")
    76        --update-max-failure-ratio float     Failure rate to tolerate during an update (default 0)
    77        --update-monitor duration            Duration after each task update to monitor for failure (ns|us|ms|s|m|h) (default 5s)
    78        --update-order string                Update order ("start-first"|"stop-first") (default "stop-first")
    79        --update-parallelism uint            Maximum number of tasks updated simultaneously (0 to update all at once) (default 1)
    80    -u, --user string                        Username or UID (format: <name|uid>[:<group|gid>])
    81        --with-registry-auth                 Send registry authentication details to swarm agents
    82    -w, --workdir string                     Working directory inside the container
    83  ```
    84  
    85  ## Description
    86  
    87  Creates a service as described by the specified parameters. You must run this
    88  command on a manager node.
    89  
    90  ## Examples
    91  
    92  ### Create a service
    93  
    94  ```bash
    95  $ docker service create --name redis redis:3.0.6
    96  
    97  dmu1ept4cxcfe8k8lhtux3ro3
    98  
    99  $ docker service create --mode global --name redis2 redis:3.0.6
   100  
   101  a8q9dasaafudfs8q8w32udass
   102  
   103  $ docker service ls
   104  
   105  ID            NAME    MODE        REPLICAS  IMAGE
   106  dmu1ept4cxcf  redis   replicated  1/1       redis:3.0.6
   107  a8q9dasaafud  redis2  global      1/1       redis:3.0.6
   108  ```
   109  
   110  ### Create a service with 5 replica tasks (--replicas)
   111  
   112  Use the `--replicas` flag to set the number of replica tasks for a replicated
   113  service. The following command creates a `redis` service with `5` replica tasks:
   114  
   115  ```bash
   116  $ docker service create --name redis --replicas=5 redis:3.0.6
   117  
   118  4cdgfyky7ozwh3htjfw0d12qv
   119  ```
   120  
   121  The above command sets the *desired* number of tasks for the service. Even
   122  though the command returns immediately, actual scaling of the service may take
   123  some time. The `REPLICAS` column shows both the *actual* and *desired* number
   124  of replica tasks for the service.
   125  
   126  In the following example the desired state is  `5` replicas, but the current
   127  number of `RUNNING` tasks is `3`:
   128  
   129  ```bash
   130  $ docker service ls
   131  
   132  ID            NAME   MODE        REPLICAS  IMAGE
   133  4cdgfyky7ozw  redis  replicated  3/5       redis:3.0.7
   134  ```
   135  
   136  Once all the tasks are created and `RUNNING`, the actual number of tasks is
   137  equal to the desired number:
   138  
   139  ```bash
   140  $ docker service ls
   141  
   142  ID            NAME   MODE        REPLICAS  IMAGE
   143  4cdgfyky7ozw  redis  replicated  5/5       redis:3.0.7
   144  ```
   145  
   146  ### Create a service with secrets
   147  
   148  Use the `--secret` flag to give a container access to a
   149  [secret](secret_create.md).
   150  
   151  Create a service specifying a secret:
   152  
   153  ```bash
   154  $ docker service create --name redis --secret secret.json redis:3.0.6
   155  
   156  4cdgfyky7ozwh3htjfw0d12qv
   157  ```
   158  
   159  Create a service specifying the secret, target, user/group ID and mode:
   160  
   161  ```bash
   162  $ docker service create --name redis \
   163      --secret source=ssh-key,target=ssh \
   164      --secret source=app-key,target=app,uid=1000,gid=1001,mode=0400 \
   165      redis:3.0.6
   166  
   167  4cdgfyky7ozwh3htjfw0d12qv
   168  ```
   169  
   170  Secrets are located in `/run/secrets` in the container.  If no target is
   171  specified, the name of the secret will be used as the in memory file in the
   172  container.  If a target is specified, that will be the filename.  In the
   173  example above, two files will be created: `/run/secrets/ssh` and
   174  `/run/secrets/app` for each of the secret targets specified.
   175  
   176  ### Create a service with a rolling update policy
   177  
   178  ```bash
   179  $ docker service create \
   180    --replicas 10 \
   181    --name redis \
   182    --update-delay 10s \
   183    --update-parallelism 2 \
   184    redis:3.0.6
   185  ```
   186  
   187  When you run a [service update](service_update.md), the scheduler updates a
   188  maximum of 2 tasks at a time, with `10s` between updates. For more information,
   189  refer to the [rolling updates
   190  tutorial](https://docs.docker.com/engine/swarm/swarm-tutorial/rolling-update/).
   191  
   192  ### Set environment variables (-e, --env)
   193  
   194  This sets environmental variables for all tasks in a service. For example:
   195  
   196  ```bash
   197  $ docker service create --name redis_2 --replicas 5 --env MYVAR=foo redis:3.0.6
   198  ```
   199  
   200  ### Create a service with specific hostname (--hostname)
   201  
   202  This option sets the docker service containers hostname to a specific string.
   203  For example:
   204  
   205  ```bash
   206  $ docker service create --name redis --hostname myredis redis:3.0.6
   207  ```
   208  
   209  ### Set metadata on a service (-l, --label)
   210  
   211  A label is a `key=value` pair that applies metadata to a service. To label a
   212  service with two labels:
   213  
   214  ```bash
   215  $ docker service create \
   216    --name redis_2 \
   217    --label com.example.foo="bar"
   218    --label bar=baz \
   219    redis:3.0.6
   220  ```
   221  
   222  For more information about labels, refer to [apply custom
   223  metadata](https://docs.docker.com/engine/userguide/labels-custom-metadata/).
   224  
   225  ### Add bind-mounts or volumes
   226  
   227  Docker supports two different kinds of mounts, which allow containers to read to
   228  or write from files or directories on other containers or the host operating
   229  system. These types are _data volumes_ (often referred to simply as volumes) and
   230  _bind-mounts_.
   231  
   232  Additionally, Docker supports `tmpfs` mounts.
   233  
   234  A **bind-mount** makes a file or directory on the host available to the
   235  container it is mounted within. A bind-mount may be either read-only or
   236  read-write. For example, a container might share its host's DNS information by
   237  means of a bind-mount of the host's `/etc/resolv.conf` or a container might
   238  write logs to its host's `/var/log/myContainerLogs` directory. If you use
   239  bind-mounts and your host and containers have different notions of permissions,
   240  access controls, or other such details, you will run into portability issues.
   241  
   242  A **named volume** is a mechanism for decoupling persistent data needed by your
   243  container from the image used to create the container and from the host machine.
   244  Named volumes are created and managed by Docker, and a named volume persists
   245  even when no container is currently using it. Data in named volumes can be
   246  shared between a container and the host machine, as well as between multiple
   247  containers. Docker uses a _volume driver_ to create, manage, and mount volumes.
   248  You can back up or restore volumes using Docker commands.
   249  
   250  A **tmpfs** mounts a tmpfs inside a container for volatile data.
   251  
   252  Consider a situation where your image starts a lightweight web server. You could
   253  use that image as a base image, copy in your website's HTML files, and package
   254  that into another image. Each time your website changed, you'd need to update
   255  the new image and redeploy all of the containers serving your website. A better
   256  solution is to store the website in a named volume which is attached to each of
   257  your web server containers when they start. To update the website, you just
   258  update the named volume.
   259  
   260  For more information about named volumes, see
   261  [Data Volumes](https://docs.docker.com/engine/tutorials/dockervolumes/).
   262  
   263  The following table describes options which apply to both bind-mounts and named
   264  volumes in a service:
   265  
   266  <table>
   267    <tr>
   268      <th>Option</th>
   269      <th>Required</th>
   270      <th>Description</th>
   271    </tr>
   272    <tr>
   273      <td><b>types</b></td>
   274      <td></td>
   275      <td>
   276        <p>The type of mount, can be either <tt>volume</tt>, <tt>bind</tt>, or <tt>tmpfs</tt>. Defaults to <tt>volume</tt> if no type is specified.
   277        <ul>
   278          <li><tt>volume</tt>: mounts a [managed volume](volume_create.md) into the container.</li>
   279          <li><tt>bind</tt>: bind-mounts a directory or file from the host into the container.</li>
   280          <li><tt>tmpfs</tt>: mount a tmpfs in the container</li>
   281        </ul></p>
   282      </td>
   283    </tr>
   284    <tr>
   285      <td><b>src</b> or <b>source</b></td>
   286      <td>for <tt>type=bind</tt> only></td>
   287      <td>
   288        <ul>
   289          <li>
   290           <tt>type=volume</tt>: <tt>src</tt> is an optional way to specify the name of the volume (for example, <tt>src=my-volume</tt>).
   291            If the named volume does not exist, it is automatically created. If no <tt>src</tt> is specified, the volume is
   292            assigned a random name which is guaranteed to be unique on the host, but may not be unique cluster-wide.
   293            A randomly-named volume has the same lifecycle as its container and is destroyed when the <i>container</i>
   294            is destroyed (which is upon <tt>service update</tt>, or when scaling or re-balancing the service)
   295          </li>
   296          <li>
   297            <tt>type=bind</tt>: <tt>src</tt> is required, and specifies an absolute path to the file or directory to bind-mount
   298            (for example, <tt>src=/path/on/host/</tt>). An error is produced if the file or directory does not exist.
   299          </li>
   300          <li>
   301            <tt>type=tmpfs</tt>: <tt>src</tt> is not supported.
   302          </li>
   303        </ul>
   304      </td>
   305    </tr>
   306    <tr>
   307      <td><p><b>dst</b> or <b>destination</b> or <b>target</b></p></td>
   308      <td>yes</td>
   309      <td>
   310        <p>Mount path inside the container, for example <tt>/some/path/in/container/</tt>.
   311        If the path does not exist in the container's filesystem, the Engine creates
   312        a directory at the specified location before mounting the volume or bind-mount.</p>
   313      </td>
   314    </tr>
   315    <tr>
   316      <td><p><b>readonly</b> or <b>ro</b></p></td>
   317      <td></td>
   318      <td>
   319        <p>The Engine mounts binds and volumes <tt>read-write</tt> unless <tt>readonly</tt> option
   320        is given when mounting the bind or volume.
   321        <ul>
   322          <li><tt>true</tt> or <tt>1</tt> or no value: Mounts the bind or volume read-only.</li>
   323          <li><tt>false</tt> or <tt>0</tt>: Mounts the bind or volume read-write.</li>
   324        </ul></p>
   325      </td>
   326    </tr>
   327    <tr>
   328      <td><b>consistency</b></td>
   329      <td></td>
   330      <td>
   331        <p>The consistency requirements for the mount; one of
   332           <ul>
   333             <li><tt>default</tt>: Equivalent to <tt>consistent</tt>.</li>
   334             <li><tt>consistent</tt>: Full consistency.  The container runtime and the host maintain an identical view of the mount at all times.</li>
   335             <li><tt>cached</tt>: The host's view of the mount is authoritative.  There may be delays before updates made on the host are visible within a container.</li>
   336             <li><tt>delegated</tt>: The container runtime's view of the mount is authoritative.  There may be delays before updates made in a container are are visible on the host.</li>
   337          </ul>
   338       </p>
   339      </td>
   340    </tr>
   341  </table>
   342  
   343  #### Bind Propagation
   344  
   345  Bind propagation refers to whether or not mounts created within a given
   346  bind-mount or named volume can be propagated to replicas of that mount. Consider
   347  a mount point `/mnt`, which is also mounted on `/tmp`. The propation settings
   348  control whether a mount on `/tmp/a` would also be available on `/mnt/a`. Each
   349  propagation setting has a recursive counterpoint. In the case of recursion,
   350  consider that `/tmp/a` is also mounted as `/foo`. The propagation settings
   351  control whether `/mnt/a` and/or `/tmp/a` would exist.
   352  
   353  The `bind-propagation` option defaults to `rprivate` for both bind-mounts and
   354  volume mounts, and is only configurable for bind-mounts. In other words, named
   355  volumes do not support bind propagation.
   356  
   357  - **`shared`**: Sub-mounts of the original mount are exposed to replica mounts,
   358                  and sub-mounts of replica mounts are also propagated to the
   359                  original mount.
   360  - **`slave`**: similar to a shared mount, but only in one direction. If the
   361                 original mount exposes a sub-mount, the replica mount can see it.
   362                 However, if the replica mount exposes a sub-mount, the original
   363                 mount cannot see it.
   364  - **`private`**: The mount is private. Sub-mounts within it are not exposed to
   365                   replica mounts, and sub-mounts of replica mounts are not
   366                   exposed to the original mount.
   367  - **`rshared`**: The same as shared, but the propagation also extends to and from
   368                   mount points nested within any of the original or replica mount
   369                   points.
   370  - **`rslave`**: The same as `slave`, but the propagation also extends to and from
   371                   mount points nested within any of the original or replica mount
   372                   points.
   373  - **`rprivate`**: The default. The same as `private`, meaning that no mount points
   374                    anywhere within the original or replica mount points propagate
   375                    in either direction.
   376  
   377  For more information about bind propagation, see the
   378  [Linux kernel documentation for shared subtree](https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt).
   379  
   380  #### Options for Named Volumes
   381  
   382  The following options can only be used for named volumes (`type=volume`);
   383  
   384  
   385  <table>
   386    <tr>
   387      <th>Option</th>
   388      <th>Description</th>
   389    </tr>
   390    <tr>
   391      <td><b>volume-driver</b></td>
   392      <td>
   393        <p>Name of the volume-driver plugin to use for the volume. Defaults to
   394        <tt>"local"</tt>, to use the local volume driver to create the volume if the
   395        volume does not exist.</p>
   396      </td>
   397    </tr>
   398    <tr>
   399      <td><b>volume-label</b></td>
   400      <td>
   401        One or more custom metadata ("labels") to apply to the volume upon
   402        creation. For example,
   403        `volume-label=mylabel=hello-world,my-other-label=hello-mars`. For more
   404        information about labels, refer to
   405        <a href="https://docs.docker.com/engine/userguide/labels-custom-metadata/">apply custom metadata</a>.
   406      </td>
   407    </tr>
   408    <tr>
   409      <td><b>volume-nocopy</b></td>
   410      <td>
   411        By default, if you attach an empty volume to a container, and files or
   412        directories already existed at the mount-path in the container (<tt>dst</tt>),
   413        the Engine copies those files and directories into the volume, allowing
   414        the host to access them. Set `volume-nocopy` to disables copying files
   415        from the container's filesystem to the volume and mount the empty volume.
   416  
   417        A value is optional:
   418  
   419        <ul>
   420          <li><tt>true</tt> or <tt>1</tt>: Default if you do not provide a value. Disables copying.</li>
   421          <li><tt>false</tt> or <tt>0</tt>: Enables copying.</li>
   422        </ul>
   423      </td>
   424    </tr>
   425    <tr>
   426      <td><b>volume-opt</b></td>
   427      <td>
   428        Options specific to a given volume driver, which will be passed to the
   429        driver when creating the volume. Options are provided as a comma-separated
   430        list of key/value pairs, for example,
   431        <tt>volume-opt=some-option=some-value,volume-opt=some-other-option=some-other-value</tt>.
   432        For available options for a given driver, refer to that driver's
   433        documentation.
   434      </td>
   435    </tr>
   436  </table>
   437  
   438  
   439  #### Options for tmpfs
   440  
   441  The following options can only be used for tmpfs mounts (`type=tmpfs`);
   442  
   443  
   444  <table>
   445    <tr>
   446      <th>Option</th>
   447      <th>Description</th>
   448    </tr>
   449    <tr>
   450      <td><b>tmpfs-size</b></td>
   451      <td>Size of the tmpfs mount in bytes. Unlimited by default in Linux.</td>
   452    </tr>
   453    <tr>
   454      <td><b>tmpfs-mode</b></td>
   455      <td>File mode of the tmpfs in octal. (e.g. <tt>"700"</tt> or <tt>"0700"</tt>.) Defaults to <tt>"1777"</tt> in Linux.</td>
   456    </tr>
   457  </table>
   458  
   459  
   460  #### Differences between "--mount" and "--volume"
   461  
   462  The `--mount` flag supports most options that are supported by the `-v`
   463  or `--volume` flag for `docker run`, with some important exceptions:
   464  
   465  - The `--mount` flag allows you to specify a volume driver and volume driver
   466    options *per volume*, without creating the volumes in advance. In contrast,
   467    `docker run` allows you to specify a single volume driver which is shared
   468    by all volumes, using the `--volume-driver` flag.
   469  
   470  - The `--mount` flag allows you to specify custom metadata ("labels") for a volume,
   471    before the volume is created.
   472  
   473  - When you use `--mount` with `type=bind`, the host-path must refer to an *existing*
   474    path on the host. The path will not be created for you and the service will fail
   475    with an error if the path does not exist.
   476  
   477  - The `--mount` flag does not allow you to relabel a volume with `Z` or `z` flags,
   478    which are used for `selinux` labeling.
   479  
   480  #### Create a service using a named volume
   481  
   482  The following example creates a service that uses a named volume:
   483  
   484  ```bash
   485  $ docker service create \
   486    --name my-service \
   487    --replicas 3 \
   488    --mount type=volume,source=my-volume,destination=/path/in/container,volume-label="color=red",volume-label="shape=round" \
   489    nginx:alpine
   490  ```
   491  
   492  For each replica of the service, the engine requests a volume named "my-volume"
   493  from the default ("local") volume driver where the task is deployed. If the
   494  volume does not exist, the engine creates a new volume and applies the "color"
   495  and "shape" labels.
   496  
   497  When the task is started, the volume is mounted on `/path/in/container/` inside
   498  the container.
   499  
   500  Be aware that the default ("local") volume is a locally scoped volume driver.
   501  This means that depending on where a task is deployed, either that task gets a
   502  *new* volume named "my-volume", or shares the same "my-volume" with other tasks
   503  of the same service. Multiple containers writing to a single shared volume can
   504  cause data corruption if the software running inside the container is not
   505  designed to handle concurrent processes writing to the same location. Also take
   506  into account that containers can be re-scheduled by the Swarm orchestrator and
   507  be deployed on a different node.
   508  
   509  #### Create a service that uses an anonymous volume
   510  
   511  The following command creates a service with three replicas with an anonymous
   512  volume on `/path/in/container`:
   513  
   514  ```bash
   515  $ docker service create \
   516    --name my-service \
   517    --replicas 3 \
   518    --mount type=volume,destination=/path/in/container \
   519    nginx:alpine
   520  ```
   521  
   522  In this example, no name (`source`) is specified for the volume, so a new volume
   523  is created for each task. This guarantees that each task gets its own volume,
   524  and volumes are not shared between tasks. Anonymous volumes are removed after
   525  the task using them is complete.
   526  
   527  #### Create a service that uses a bind-mounted host directory
   528  
   529  The following example bind-mounts a host directory at `/path/in/container` in
   530  the containers backing the service:
   531  
   532  ```bash
   533  $ docker service create \
   534    --name my-service \
   535    --mount type=bind,source=/path/on/host,destination=/path/in/container \
   536    nginx:alpine
   537  ```
   538  
   539  ### Set service mode (--mode)
   540  
   541  The service mode determines whether this is a _replicated_ service or a _global_
   542  service. A replicated service runs as many tasks as specified, while a global
   543  service runs on each active node in the swarm.
   544  
   545  The following command creates a global service:
   546  
   547  ```bash
   548  $ docker service create \
   549   --name redis_2 \
   550   --mode global \
   551   redis:3.0.6
   552  ```
   553  
   554  ### Specify service constraints (--constraint)
   555  
   556  You can limit the set of nodes where a task can be scheduled by defining
   557  constraint expressions. Multiple constraints find nodes that satisfy every
   558  expression (AND match). Constraints can match node or Docker Engine labels as
   559  follows:
   560  
   561  
   562  <table>
   563    <tr>
   564      <th>node attribute</th>
   565      <th>matches</th>
   566      <th>example</th>
   567    </tr>
   568    <tr>
   569      <td><tt>node.id</tt></td>
   570      <td>Node ID</td>
   571      <td><tt>node.id == 2ivku8v2gvtg4</tt></td>
   572    </tr>
   573    <tr>
   574      <td><tt>node.hostname</tt></td>
   575      <td>Node hostname</td>
   576      <td><tt>node.hostname != node-2</tt></td>
   577    </tr>
   578    <tr>
   579      <td><tt>node.role</tt></td>
   580      <td>Node role</td>
   581      <td><tt>node.role == manager</tt></td>
   582    </tr>
   583    <tr>
   584      <td><tt>node.labels</tt></td>
   585      <td>user defined node labels</td>
   586      <td><tt>node.labels.security == high</tt></td>
   587    </tr>
   588    <tr>
   589      <td><tt>engine.labels</tt></td>
   590      <td>Docker Engine's labels</td>
   591      <td><tt>engine.labels.operatingsystem == ubuntu 14.04</tt></td>
   592    </tr>
   593  </table>
   594  
   595  
   596  `engine.labels` apply to Docker Engine labels like operating system,
   597  drivers, etc. Swarm administrators add `node.labels` for operational purposes by
   598  using the [`docker node update`](node_update.md) command.
   599  
   600  For example, the following limits tasks for the redis service to nodes where the
   601  node type label equals queue:
   602  
   603  ```bash
   604  $ docker service create \
   605    --name redis_2 \
   606    --constraint 'node.labels.type == queue' \
   607    redis:3.0.6
   608  ```
   609  
   610  ### Specify service placement preferences (--placement-pref)
   611  
   612  You can set up the service to divide tasks evenly over different categories of
   613  nodes. One example of where this can be useful is to balance tasks over a set
   614  of datacenters or availability zones. The example below illustrates this:
   615  
   616  ```bash
   617  $ docker service create \
   618    --replicas 9 \
   619    --name redis_2 \
   620    --placement-pref 'spread=node.labels.datacenter' \
   621    redis:3.0.6
   622  ```
   623  
   624  This uses `--placement-pref` with a `spread` strategy (currently the only
   625  supported strategy) to spread tasks evenly over the values of the `datacenter`
   626  node label. In this example, we assume that every node has a `datacenter` node
   627  label attached to it. If there are three different values of this label among
   628  nodes in the swarm, one third of the tasks will be placed on the nodes
   629  associated with each value. This is true even if there are more nodes with one
   630  value than another. For example, consider the following set of nodes:
   631  
   632  - Three nodes with `node.labels.datacenter=east`
   633  - Two nodes with `node.labels.datacenter=south`
   634  - One node with `node.labels.datacenter=west`
   635  
   636  Since we are spreading over the values of the `datacenter` label and the
   637  service has 9 replicas, 3 replicas will end up in each datacenter. There are
   638  three nodes associated with the value `east`, so each one will get one of the
   639  three replicas reserved for this value. There are two nodes with the value
   640  `south`, and the three replicas for this value will be divided between them,
   641  with one receiving two replicas and another receiving just one. Finally, `west`
   642  has a single node that will get all three replicas reserved for `west`.
   643  
   644  If the nodes in one category (for example, those with
   645  `node.labels.datacenter=south`) can't handle their fair share of tasks due to
   646  constraints or resource limitations, the extra tasks will be assigned to other
   647  nodes instead, if possible.
   648  
   649  Both engine labels and node labels are supported by placement preferences. The
   650  example above uses a node label, because the label is referenced with
   651  `node.labels.datacenter`. To spread over the values of an engine label, use
   652  `--placement-pref spread=engine.labels.<labelname>`.
   653  
   654  It is possible to add multiple placement preferences to a service. This
   655  establishes a hierarchy of preferences, so that tasks are first divided over
   656  one category, and then further divided over additional categories. One example
   657  of where this may be useful is dividing tasks fairly between datacenters, and
   658  then splitting the tasks within each datacenter over a choice of racks. To add
   659  multiple placement preferences, specify the `--placement-pref` flag multiple
   660  times. The order is significant, and the placement preferences will be applied
   661  in the order given when making scheduling decisions.
   662  
   663  The following example sets up a service with multiple placement preferences.
   664  Tasks are spread first over the various datacenters, and then over racks
   665  (as indicated by the respective labels):
   666  
   667  ```bash
   668  $ docker service create \
   669    --replicas 9 \
   670    --name redis_2 \
   671    --placement-pref 'spread=node.labels.datacenter' \
   672    --placement-pref 'spread=node.labels.rack' \
   673    redis:3.0.6
   674  ```
   675  
   676  When updating a service with `docker service update`, `--placement-pref-add`
   677  appends a new placement preference after all existing placement preferences.
   678  `--placement-pref-rm` removes an existing placement preference that matches the
   679  argument.
   680  
   681  ### Attach a service to an existing network (--network)
   682  
   683  You can use overlay networks to connect one or more services within the swarm.
   684  
   685  First, create an overlay network on a manager node the docker network create
   686  command:
   687  
   688  ```bash
   689  $ docker network create --driver overlay my-network
   690  
   691  etjpu59cykrptrgw0z0hk5snf
   692  ```
   693  
   694  After you create an overlay network in swarm mode, all manager nodes have
   695  access to the network.
   696  
   697  When you create a service and pass the --network flag to attach the service to
   698  the overlay network:
   699  
   700  ```bash
   701  $ docker service create \
   702    --replicas 3 \
   703    --network my-network \
   704    --name my-web \
   705    nginx
   706  
   707  716thylsndqma81j6kkkb5aus
   708  ```
   709  
   710  The swarm extends my-network to each node running the service.
   711  
   712  Containers on the same network can access each other using
   713  [service discovery](https://docs.docker.com/engine/swarm/networking/#use-swarm-mode-service-discovery).
   714  
   715  ### Publish service ports externally to the swarm (-p, --publish)
   716  
   717  You can publish service ports to make them available externally to the swarm
   718  using the `--publish` flag:
   719  
   720  ```bash
   721  $ docker service create --publish <TARGET-PORT>:<SERVICE-PORT> nginx
   722  ```
   723  
   724  For example:
   725  
   726  ```bash
   727  $ docker service create --name my_web --replicas 3 --publish 8080:80 nginx
   728  ```
   729  
   730  When you publish a service port, the swarm routing mesh makes the service
   731  accessible at the target port on every node regardless if there is a task for
   732  the service running on the node. For more information refer to
   733  [Use swarm mode routing mesh](https://docs.docker.com/engine/swarm/ingress/).
   734  
   735  ### Publish a port for TCP only or UDP only
   736  
   737  By default, when you publish a port, it is a TCP port. You can
   738  specifically publish a UDP port instead of or in addition to a TCP port. When
   739  you publish both TCP and UDP ports, Docker 1.12.2 and earlier require you to
   740  add the suffix `/tcp` for TCP ports. Otherwise it is optional.
   741  
   742  #### TCP only
   743  
   744  The following two commands are equivalent.
   745  
   746  ```bash
   747  $ docker service create --name dns-cache -p 53:53 dns-cache
   748  
   749  $ docker service create --name dns-cache -p 53:53/tcp dns-cache
   750  ```
   751  
   752  #### TCP and UDP
   753  
   754  ```bash
   755  $ docker service create --name dns-cache -p 53:53/tcp -p 53:53/udp dns-cache
   756  ```
   757  
   758  #### UDP only
   759  
   760  ```bash
   761  $ docker service create --name dns-cache -p 53:53/udp dns-cache
   762  ```
   763  
   764  ### Create services using templates
   765  
   766  You can use templates for some flags of `service create`, using the syntax
   767  provided by the Go's [text/template](http://golang.org/pkg/text/template/) package.
   768  
   769  The supported flags are the following :
   770  
   771  - `--hostname`
   772  - `--mount`
   773  - `--env`
   774  
   775  Valid placeholders for the Go template are listed below:
   776  
   777  
   778  <table>
   779    <tr>
   780      <th>Placeholder</th>
   781      <th>Description</th>
   782    </tr>
   783    <tr>
   784      <td><tt>.Service.ID</tt></td>
   785      <td>Service ID</td>
   786    </tr>
   787    <tr>
   788      <td><tt>.Service.Name</tt></td>
   789      <td>Service name</td>
   790    </tr>
   791    <tr>
   792      <td><tt>.Service.Labels</tt></td>
   793      <td>Service labels</td>
   794    </tr>
   795    <tr>
   796      <td><tt>.Node.ID</tt></td>
   797      <td>Node ID</td>
   798    </tr>
   799    <tr>
   800      <td><tt>.Task.ID</tt></td>
   801      <td>Task ID</td>
   802    </tr>
   803    <tr>
   804      <td><tt>.Task.Name</tt></td>
   805      <td>Task name</td>
   806    </tr>
   807    <tr>
   808      <td><tt>.Task.Slot</tt></td>
   809      <td>Task slot</td>
   810    </tr>
   811  </table>
   812  
   813  
   814  #### Template example
   815  
   816  In this example, we are going to set the template of the created containers based on the
   817  service's name and the node's ID where it sits.
   818  
   819  ```bash
   820  $ docker service create --name hosttempl \
   821                          --hostname="{{.Node.ID}}-{{.Service.Name}}"\
   822                           busybox top
   823  
   824  va8ew30grofhjoychbr6iot8c
   825  
   826  $ docker service ps va8ew30grofhjoychbr6iot8c
   827  
   828  ID            NAME         IMAGE                                                                                   NODE          DESIRED STATE  CURRENT STATE               ERROR  PORTS
   829  wo41w8hg8qan  hosttempl.1  busybox:latest@sha256:29f5d56d12684887bdfa50dcd29fc31eea4aaf4ad3bec43daf19026a7ce69912  2e7a8a9c4da2  Running        Running about a minute ago
   830  
   831  $ docker inspect --format="{{.Config.Hostname}}" hosttempl.1.wo41w8hg8qanxwjwsg4kxpprj
   832  
   833  x3ti0erg11rjpg64m75kej2mz-hosttempl
   834  ```
   835  
   836  ## Related commands
   837  
   838  * [service inspect](service_inspect.md)
   839  * [service logs](service_logs.md)
   840  * [service ls](service_ls.md)
   841  * [service rm](service_rm.md)
   842  * [service scale](service_scale.md)
   843  * [service ps](service_ps.md)
   844  * [service update](service_update.md)
   845  
   846  <style>table tr > td:first-child { white-space: nowrap;}</style>