Today is the last day , We finally stop the container , Delete function to achieve
Container stop
In the last section , We go through
config.json
The basic information of the container is recorded , One of themstatus
Field is used to record the state of the container , And a PID Field record containerinit
Process on the host Pid, We stop the container , That is to say pid The process to kill , And update the status Status can be
// Stop container , Modify the container state
func StopContainer(containerName string) {
info, err := getContainerInfo(containerName)
if err != nil {
logrus.Errorf("get container info, err: %v", err)
return
}
if info.Pid != "" {
pid, _ := strconv.Atoi(info.Pid)
// Kill process
if err := syscall.Kill(pid, syscall.SIGTERM); err != nil {
logrus.Errorf("stop container, pid: %d, err: %v", pid, err)
return
}
// Modify the container state
info.Status = common.Stop
info.Pid = ""
bs, _ := json.Marshal(info)
fileName := path.Join(common.DefaultContainerInfoPath, containerName, common.ContainerInfoFileName)
err := ioutil.WriteFile(fileName, bs, 0622)
if err != nil {
logrus.Errorf("write container config.json, err: %v", err)
}
}
}
Delete container
First of all, it needs to be clear , We can’t delete running containers , That is to say
status
byRunning
The container of , So we must stop the container before we delete it , Then we delete a series of folders generated by the container
// Delete container
func RemoveContainer(containerName string) {
info, err := getContainerInfo(containerName)
if err != nil {
logrus.Errorf("get container info, err: %v", err)
return
}
// You can only delete containers in the stopped state
if info.Status != common.Stop {
logrus.Errorf("can't remove running container")
return
}
dir := path.Join(common.DefaultContainerInfoPath, containerName)
err = os.RemoveAll(dir)
if err != nil {
logrus.Errorf("remove container dir: %s, err: %v", dir, err)
return
}
}
Here we are 《 For seven days Go Write a docker》 The system article is over , Finally, thank you for your attention and support ! All the source code of the article has been in GitHub Open source , Click here