github.com/kim0/docker@v0.6.2-0.20161130212042-4addda3f07e7/cli/command/service/create.go (about) 1 package service 2 3 import ( 4 "fmt" 5 6 "github.com/docker/docker/api/types" 7 "github.com/docker/docker/cli" 8 "github.com/docker/docker/cli/command" 9 "github.com/spf13/cobra" 10 "golang.org/x/net/context" 11 ) 12 13 func newCreateCommand(dockerCli *command.DockerCli) *cobra.Command { 14 opts := newServiceOptions() 15 16 cmd := &cobra.Command{ 17 Use: "create [OPTIONS] IMAGE [COMMAND] [ARG...]", 18 Short: "Create a new service", 19 Args: cli.RequiresMinArgs(1), 20 RunE: func(cmd *cobra.Command, args []string) error { 21 opts.image = args[0] 22 if len(args) > 1 { 23 opts.args = args[1:] 24 } 25 return runCreate(dockerCli, opts) 26 }, 27 } 28 flags := cmd.Flags() 29 flags.StringVar(&opts.mode, flagMode, "replicated", "Service mode (replicated or global)") 30 flags.StringVar(&opts.name, flagName, "", "Service name") 31 32 addServiceFlags(cmd, opts) 33 34 flags.VarP(&opts.labels, flagLabel, "l", "Service labels") 35 flags.Var(&opts.containerLabels, flagContainerLabel, "Container labels") 36 flags.VarP(&opts.env, flagEnv, "e", "Set environment variables") 37 flags.Var(&opts.envFile, flagEnvFile, "Read in a file of environment variables") 38 flags.Var(&opts.mounts, flagMount, "Attach a mount to the service") 39 flags.StringSliceVar(&opts.constraints, flagConstraint, []string{}, "Placement constraints") 40 flags.StringSliceVar(&opts.networks, flagNetwork, []string{}, "Network attachments") 41 flags.VarP(&opts.endpoint.ports, flagPublish, "p", "Publish a port as a node port") 42 flags.StringSliceVar(&opts.groups, flagGroup, []string{}, "Set one or more supplementary user groups for the container") 43 44 flags.SetInterspersed(false) 45 return cmd 46 } 47 48 func runCreate(dockerCli *command.DockerCli, opts *serviceOptions) error { 49 apiClient := dockerCli.Client() 50 createOpts := types.ServiceCreateOptions{} 51 52 service, err := opts.ToService() 53 if err != nil { 54 return err 55 } 56 57 ctx := context.Background() 58 59 // only send auth if flag was set 60 if opts.registryAuth { 61 // Retrieve encoded auth token from the image reference 62 encodedAuth, err := command.RetrieveAuthTokenFromImage(ctx, dockerCli, opts.image) 63 if err != nil { 64 return err 65 } 66 createOpts.EncodedRegistryAuth = encodedAuth 67 } 68 69 response, err := apiClient.ServiceCreate(ctx, service, createOpts) 70 if err != nil { 71 return err 72 } 73 74 fmt.Fprintf(dockerCli.Out(), "%s\n", response.ID) 75 return nil 76 }