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