如何生成docker容器ID

时间:2015-10-08 10:06:31

标签: docker

我想知道如何生成容器ID所以请在执行docker run时提供提供容器ID的源代码?

1 个答案:

答案 0 :(得分:8)

以下是docker守护程序用于创建容器的函数的代码片段:

func (daemon *Daemon) newContainer(name string, config *runconfig.Config, imgID string) (*Container, error) {
    var (
        id  string
        err error
    )
    id, name, err = daemon.generateIDAndName(name)
    if err != nil {
        return nil, err
    }

    …

    base := daemon.newBaseContainer(id)

    …

    base.ExecDriver = daemon.execDriver.Name()

    return &base, err
}

因此,创建ID和Name的逻辑在generateIDAndName函数中:

func (daemon *Daemon) generateIDAndName(name string) (string, string, error) {
    var (
        err error
        id  = stringid.GenerateNonCryptoID()
    )

    if name == "" {
        if name, err = daemon.generateNewName(id); err != nil {
            return "", "", err
        }
        return id, name, nil
    }

    if name, err = daemon.reserveName(id, name); err != nil {
        return "", "", err
    }

    return id, name, nil
}

这是stringid sources,具体方法是generateID,输入参数为false:

func generateID(crypto bool) string {
    b := make([]byte, 32)
    var r io.Reader = random.Reader
    if crypto {
        r = rand.Reader
    }
    for {
        if _, err := io.ReadFull(r, b); err != nil {
            panic(err) // This shouldn't happen
        }
        id := hex.EncodeToString(b)
        // if we try to parse the truncated for as an int and we don't have
        // an error then the value is all numberic and causes issues when
        // used as a hostname. ref #3869
        if _, err := strconv.ParseInt(TruncateID(id), 10, 64); err == nil {
            continue
        }
        return id
    }
}

如您所见,该值是使用此random

随机生成的
// Reader is a global, shared instance of a pseudorandom bytes generator.
// It doesn't consume entropy.
var Reader io.Reader = &reader{rnd: Rand}