顯示具有 docker 標籤的文章。 顯示所有文章
顯示具有 docker 標籤的文章。 顯示所有文章

init mongodb data in docker

 1. Given file in project folder ./mongo/docker-entrypoint-initdb.d:/initdb.sh

```

echo '=====================================>'

mongo --eval 'db.getSiblingDB("testqq").createUser({"user": "admin", "pwd": "admin", roles: [{"role": "readWrite","db": "testqq"}]});'

mongo --eval 'db.getSiblingDB("testqq").users.insert({"username" : "admin", "password" : "admin", "email" : "admin@gmail.com"});'

echo '<======================================'

```


2. Given docker-compose.yml

```

services:

  mongo:

    image: mongo:4.4

    ports:

      - "27017:27017"

    volumes:

    - "./mongo/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d"

```


3. Start docker-compose

```

$ docker-compose up

```


4. Check log, can find following log

```

mongo_1  | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/initdb.sh

mongo_1  | =====================================>

mongo_1  | MongoDB shell version v4.4.3

mongo_1  | connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.786+00:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"127.0.0.1:46062","connectionId":2,"connectionCount":1}}

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.787+00:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn2","msg":"client metadata","attr":{"remote":"127.0.0.1:46062","client":"conn2","doc":{"application":{"name":"MongoDB Shell"},"driver":{"name":"MongoDB Internal Client","version":"4.4.3"},"os":{"type":"Linux","name":"Ubuntu","architecture":"x86_64","version":"18.04"}}}}

mongo_1  | Implicit session: session { "id" : UUID("14d8434a-7c74-4509-a5de-d55a4c63bdf4") }

mongo_1  | MongoDB server version: 4.4.3

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.835+00:00"},"s":"I",  "c":"STORAGE",  "id":20320,   "ctx":"conn2","msg":"createCollection","attr":{"namespace":"admin.system.users","uuidDisposition":"generated","uuid":{"uuid":{"$uuid":"e8923719-dd5a-4a94-a417-bb32a7ca4ebc"}},"options":{}}}

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.854+00:00"},"s":"I",  "c":"INDEX",    "id":20345,   "ctx":"conn2","msg":"Index build: done building","attr":{"buildUUID":null,"namespace":"admin.system.users","index":"_id_","commitTimestamp":{"$timestamp":{"t":0,"i":0}}}}

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.854+00:00"},"s":"I",  "c":"INDEX",    "id":20345,   "ctx":"conn2","msg":"Index build: done building","attr":{"buildUUID":null,"namespace":"admin.system.users","index":"user_1_db_1","commitTimestamp":{"$timestamp":{"t":0,"i":0}}}}

mongo_1  | Successfully added user: {

mongo_1  | "user" : "admin",

mongo_1  | "roles" : [

mongo_1  | {

mongo_1  | "role" : "readWrite",

mongo_1  | "db" : "testqq"

mongo_1  | }

mongo_1  | ]

mongo_1  | }

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.859+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn2","msg":"Connection ended","attr":{"remote":"127.0.0.1:46062","connectionId":2,"connectionCount":0}}

mongo_1  | MongoDB shell version v4.4.3

mongo_1  | connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.926+00:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"127.0.0.1:46064","connectionId":3,"connectionCount":1}}

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.927+00:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn3","msg":"client metadata","attr":{"remote":"127.0.0.1:46064","client":"conn3","doc":{"application":{"name":"MongoDB Shell"},"driver":{"name":"MongoDB Internal Client","version":"4.4.3"},"os":{"type":"Linux","name":"Ubuntu","architecture":"x86_64","version":"18.04"}}}}

mongo_1  | Implicit session: session { "id" : UUID("b0df77be-4789-4cb7-a1d0-6b64717b0207") }

mongo_1  | MongoDB server version: 4.4.3

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.937+00:00"},"s":"I",  "c":"STORAGE",  "id":20320,   "ctx":"conn3","msg":"createCollection","attr":{"namespace":"testqq.users","uuidDisposition":"generated","uuid":{"uuid":{"$uuid":"fb550551-8a86-4f98-9a93-b324e057084d"}},"options":{}}}

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.950+00:00"},"s":"I",  "c":"INDEX",    "id":20345,   "ctx":"conn3","msg":"Index build: done building","attr":{"buildUUID":null,"namespace":"testqq.users","index":"_id_","commitTimestamp":{"$timestamp":{"t":0,"i":0}}}}

mongo_1  | WriteResult({ "nInserted" : 1 })

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.957+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn3","msg":"Connection ended","attr":{"remote":"127.0.0.1:46064","connectionId":3,"connectionCount":0}}

mongo_1  | <======================================

```


5. Access mongo and check db

```

cds % docker exec -it cds_mongo_1 bash

root@186eb2a0f48d:/# mongo

MongoDB shell version v4.4.3

connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb

Implicit session: session { "id" : UUID("59729a8b-ecb1-439a-ab9f-63cc06f30e54") }

MongoDB server version: 4.4.3

Welcome to the MongoDB shell.

For interactive help, type "help".

For more comprehensive documentation, see

https://docs.mongodb.com/

Questions? Try the MongoDB Developer Community Forums

https://community.mongodb.com

---

The server generated these startup warnings when booting:

        2021-01-25T16:52:03.600+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem

        2021-01-25T16:52:04.496+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted

---

---

        Enable MongoDB's free cloud-based monitoring service, which will then receive and display

        metrics about your deployment (disk utilization, CPU, operation statistics, etc).


        The monitoring data will be available on a MongoDB website with a unique URL accessible to you

        and anyone you share the URL with. MongoDB may use this information to make product

        improvements and to suggest MongoDB products and deployment options to you.


        To enable free monitoring, run the following command: db.enableFreeMonitoring()

        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()

---

> db.getSiblingDB('testqq').getUsers()

[

{

"_id" : "testqq.admin",

"userId" : UUID("886d3d0f-7457-4724-8ae6-d9494382bce4"),

"user" : "admin",

"db" : "testqq",

"roles" : [

{

"role" : "readWrite",

"db" : "testqq"

}

],

"mechanisms" : [

"SCRAM-SHA-1",

"SCRAM-SHA-256"

]

}

]

>

```

Start Kafka by docker-compose

  1. docker-compose.yml
services:  
  zookeeper-server:
    image: bitnami/zookeeper:latest
    ports:
    - "2181:2181"
    environment:
      - ALLOW_ANONYMOUS_LOGIN=yes
    
  kafka-server:
    image: bitnami/kafka:latest
    ports:
    - "9092:9092"
    environment:
      - ALLOW_PLAINTEXT_LISTENER=yes
      - KAFKA_CFG_ZOOKEEPER_CONNECT=zookeeper-server:2181
      - KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://localhost:9092

  1. Start Kafka
docker-compose up -d
  1. Stop kafka
docker-compose down

Spring Data Reactive Cassandra CRUD

 Git branch


Cassandra commands
sudo docker run --name test-cassandra -p 9042:9042 -d cassandra:latest
sudo docker run --name test-cassandra-2 --link test-cassandra:cassandra -d cassandra:latest

docker exec -it test-cassandra /bin/bash

cqlsh> CREATE KEYSPACE test WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 3 } AND DURABLE_WRITES = false;

cqlsh> use test;

cqlsh:test> CREATE TABLE person ( id text PRIMARY KEY, name text );

Person.java
@Data
public class Person {

    @PrimaryKey private String id;
    private String name;

}

ReactivePersonRepository.java
public interface ReactivePersonRepository extends ReactiveCassandraRepository<Person, String> {}

ReactivePersonService.java
@Service
public class ReactivePersonService {

    @Autowired
    private ReactivePersonRepository reactivePersonRepository;

    public Mono<Person> save(Person person) {
        return reactivePersonRepository.save(person);
    }

    public Mono<Person> findById(String id) {
        return reactivePersonRepository.findById(id);
    }

    public Flux<Person> findAll() {
        return reactivePersonRepository.findAll();
    }

    public Mono<Void> deleteById(String id) {
        return reactivePersonRepository.deleteById(id);
    }

    public Mono<Void> deleteAll() {
        return reactivePersonRepository.deleteAll();
    }

}

ReactivePersonController.java
@RestController
@RequestMapping("/api/v2/")
public class ReactivePersonController {

    @Autowired
    private ReactivePersonService reactivePersonService;

    @PostMapping(value = "/person", consumes = "application/json")
    public Mono<Person> createPerson(@RequestBody Person person) {
        System.out.println("create person" + person);
        person.setId(UUID.randomUUID().toString());
        return reactivePersonService.save(person);
    }

    @GetMapping(value = "/person")
    public Mono<Person> getPerson(@RequestParam String id) {
        return reactivePersonService.findById(id);
    }

    @GetMapping(value = "/persons")
    public Flux<Person> getAllPersons() {
        return reactivePersonService.findAll();
    }

    @DeleteMapping("/person/{id}")
    public Mono<Void> deletePerson(@PathVariable String id) {
        return reactivePersonService.deleteById(id);
    }

    @DeleteMapping("/persons")
    public Mono<Void> deleteAll() {
        return reactivePersonService.deleteAll();
    }

Docker - force delete all containers or images


  • Force rm containers: docker container rm ${docker container ls -aq} -f
# Here is container
isaac@isaac-KVM:~$ docker container ls
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
c1b65461eefd        nginx               "nginx -g 'daemon of…"   4 days ago          Up 4 days           0.0.0.0:1234->80/tcp   webwww

# container ls -aq can show container id
isaac@isaac-KVM:~$ docker container ls -aq
c1b65461eefd

# Force remove container by query container id
isaac@isaac-KVM:~$ docker container rm $(docker container ls -aq) -f
c1b65461eefd

# Confirmed container doesn't exist
isaac@isaac-KVM:~$ docker container ls -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
isaac@isaac-KVM:~$

  • Force rm images
# There are images
isaac@isaac-KVM:~$ docker image ls -a
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              719cd2e3ed04        2 months ago        109MB
ubuntu              latest              7698f282e524        3 months ago        69.9MB

# List image ids
isaac@isaac-KVM:~$ docker image ls -aq
719cd2e3ed04
7698f282e524

# Force remove all images
isaac@isaac-KVM:~$ docker image rm $(docker image ls -aq) -f
Untagged: nginx:latest
Untagged: nginx@sha256:bdbf36b7f1f77ffe7bd2a32e59235dff6ecf131e3b6b5b96061c652f30685f3a
Deleted: sha256:719cd2e3ed04781b11ed372ec8d712fac66d5b60a6fb6190bf76b7d18cb50105
Deleted: sha256:e9b6506fb887de50972aefd99d7c5eb56b1a8e757ed953cdfecb86b5359bcb22
Deleted: sha256:55d9d9692a9615a28d183a42bc3881a72a39393feba3664e669e7affb78daa76
Deleted: sha256:cf5b3c6798f77b1f78bf4e297b27cfa5b6caa982f04caeb5de7d13c255fd7a1e
Untagged: ubuntu:latest
Untagged: ubuntu@sha256:f08638ec7ddc90065187e7eabdfac3c96e5ff0f6b2f1762cf31a4f49b53000a5
Deleted: sha256:7698f282e5242af2b9d2291458d4e425c75b25b0008c1e058d66b717b4c06fa9
Deleted: sha256:027b23fdf3957673017df55aa29d754121aee8a7ed5cc2898856f898e9220d2c
Deleted: sha256:0dfbdc7dee936a74958b05bc62776d5310abb129cfde4302b7bcdf0392561496
Deleted: sha256:02571d034293cb241c078d7ecbf7a84b83a5df2508f11a91de26ec38eb6122f1

# Confirm all images don't exist
isaac@isaac-KVM:~$ docker image ls -a
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
isaac@isaac-KVM:~$


Docker - Inspect image: understand the default command of an image

  • Inspect an image can understand what command will be executed by default

docker image inspect ubuntu
[
    {
        "Id": "sha256:a2a15febcdf362f6115e801d37b5e60d6faaeedcb9896155e5fe9d754025be12",
        "RepoTags": [
            "ubuntu:latest"
        ],
        "RepoDigests": [
            "ubuntu@sha256:d1d454df0f579c6be4d8161d227462d69e163a8ff9d20a847533989cf0c94d90"
        ],
        "Parent": "",
        "Comment": "",
        "Created": "2019-08-15T07:28:14.830150536Z",
        "Container": "41b694b9b42f9c5ef7fb40c24272927a727a6d6cb8120bb3eae5849ceb9bee77",
        "ContainerConfig": {
            "Hostname": "41b694b9b42f",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "#(nop) ",
                "CMD [\"/bin/bash\"]"
            ],
            "ArgsEscaped": true,
            "Image": "sha256:bcbe079849fdbb50b3eb04798547e046bdbc82020b8b780d767cf29f7e60b396",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {}
        },
        "DockerVersion": "18.06.1-ce",
        "Author": "",
        "Config": {
            "Hostname": "",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "ArgsEscaped": true,
            "Image": "sha256:bcbe079849fdbb50b3eb04798547e046bdbc82020b8b780d767cf29f7e60b396",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": null
        },
        "Architecture": "amd64",
        "Os": "linux",
        "Size": 64185488,
        "VirtualSize": 64185488,
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/b6f45f91ad1f6356deb2c2ab3d04305cfcf0a5eedd3fed58e7059f901fbf6c4d/diff:/var/lib/docker/overlay2/dd6b618cd5cb79f5e029942234a1aeadead024082bade5bd2321e77eb504d6f1/diff:/var/lib/docker/overlay2/0fec4af91d36748a2b39c11fcd7f73bc015144ea28c7ff4234948d97e5d839b2/diff",
                "MergedDir": "/var/lib/docker/overlay2/462cef4adf522157e3ca7b7a86af6341f141c21da54e30234c2a35264a01dae4/merged",
                "UpperDir": "/var/lib/docker/overlay2/462cef4adf522157e3ca7b7a86af6341f141c21da54e30234c2a35264a01dae4/diff",
                "WorkDir": "/var/lib/docker/overlay2/462cef4adf522157e3ca7b7a86af6341f141c21da54e30234c2a35264a01dae4/work"
            },
            "Name": "overlay2"
        },
        "RootFS": {
            "Type": "layers",
            "Layers": [
                "sha256:6cebf3abed5fac58d2e792ce8461454e92c245d5312c42118f02e231a73b317f",
                "sha256:f7eae43028b334123c3a1d778f7bdf9783bbe651c8b15371df0120fd13ec35c5",
                "sha256:7beb13bce073c21c9ee608acb13c7e851845245dc76ce81b418fdf580c45076b",
                "sha256:122be11ab4a29e554786b4a1ec4764dd55656b59d6228a0a3de78eaf5c1f226c"
            ]
        },
        "Metadata": {
            "LastTagTime": "0001-01-01T00:00:00Z"
        }
    }
]
Liaos-MBP:scg-control liaoisaac$ 

Docker - start nginx with port mapping


  • Start container in background: run -d (for running in background) with port mapping
# Pull nginx 
isaac@isaac-KVM:~$ docker pull nginx:latest
latest: Pulling from library/nginx
fc7181108d40: Pull complete
c4277fc40ec2: Pull complete
780053e98559: Pull complete
Digest: sha256:bdbf36b7f1f77ffe7bd2a32e59235dff6ecf131e3b6b5b96061c652f30685f3a
Status: Downloaded newer image for nginx:latest
isaac@isaac-KVM:~$
isaac@isaac-KVM:~$ docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              719cd2e3ed04        4 days ago          109MB
ubuntu              latest              7698f282e524        4 weeks ago         69.9MB

# Start nginx, specify port mapping from 1234 to 80 in container
isaac@isaac-KVM:~$ docker container run -d --name webwww -p 0.0.0.0:1234:80 nginx
c1b65461eefde6a3e86509602982e2eeaf7616838efa369d5504b2c9c412f8db

# List container, confirmed port mapping
isaac@isaac-KVM:~$ docker container ls
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
c1b65461eefd        nginx               "nginx -g 'daemon of…"   9 hours ago         Up 9 hours          0.0.0.0:1234->80/tcp   webwww

# Test 80 port is unreachable
isaac@isaac-KVM:~$ curl http://10.206.84.167:80
curl: (7) Failed to connect to 10.206.84.167 port 80: Connection refused

# Test 1234 port is available
isaac@isaac-KVM:~$ curl http://10.206.84.167:1234
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>


<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>


<p><em>Thank you for using nginx.</em></p>
</body>
</html>

Docker - container - restart policy


Policies
  • always
  • unless-stopped
  • on-failure

Always
  1. Always restart
  2. Unless use command to stop it
  3. Restart when docker restart, even it has been stopped by command
Ex. docker container run -it {name} --restart always
Ex. After exit the shell, container will stop because the only one process was killed. But it will be restarted right away.
# Run container
Liaos-MBP:scg-control liaoisaac$ docker container run -it ubuntu /bin/bash

# There is only one process -> /bin/bash
root@1888da48ff01:/# ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  1.3  0.1  18504  3352 pts/0    Ss   05:03   0:00 /bin/bash
root        11  0.0  0.1  34396  2912 pts/0    R+   05:03   0:00 ps aux
root@1888da48ff01:/# exit
exit

# Once exit, container will be stopped because there is only one process in container
Liaos-MBP:scg-control liaoisaac$ docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
Liaos-MBP:scg-control liaoisaac$

# Specify --restart always after “run"
Liaos-MBP:scg-control liaoisaac$ docker container run --restart always -it ubuntu /bin/bash
root@912e47da3142:/# ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.5  0.1  18504  3444 pts/0    Ss   05:11   0:00 /bin/bash
root        10  0.0  0.1  34396  2808 pts/0    R+   05:12   0:00 ps aux
root@912e47da3142:/# exit
exit

# Once exit, container will be restarted right away
Liaos-MBP:scg-control liaoisaac$ docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
912e47da3142        ubuntu              "/bin/bash"         17 seconds ago      Up 2 seconds                            hungry_khorana
Liaos-MBP:scg-control liaoisaac$


Liaos-MBP:scg-control liaoisaac$ docker stop 912e47da3142
912e47da3142
Liaos-MBP:scg-control liaoisaac$ docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

# After restart docker in Mac, applications will be restarted
Liaos-MBP:scg-control liaoisaac$ docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
912e47da3142        ubuntu              "/bin/bash"         2 days ago          Up 13 seconds                           hungry_khoran

# After docker restart, container will be restarted again
# Following is ubuntu example
isaac@isaac-KVM:~$ service docker restart
==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
Authentication is required to restart 'docker.service'.
Authenticating as: isaac,,, (isaac)
Password:
==== AUTHENTICATION COMPLETE ===
isaac@isaac-KVM:~$ docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
e4403fafa5bb        ubuntu              "/bin/bash"         3 minutes ago       Up 5 seconds                            optimistic_leh                                             mann




unless-stopped
  1. Always restart unless it is stopped by command
  2. Wont restart when daemon restart
  3. Ex. — restart unless-stopped
# Start bash with unless-stopped
isaac@isaac-KVM:~$ docker container run --restart unless-stopped -it ubuntu /bin/bash
root@3be8ac8498a7:/# ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  4.8  0.0  18504  3536 pts/0    Ss   17:53   0:00 /bin/bash
root        10  0.0  0.0  34396  2936 pts/0    R+   17:53   0:00 ps aux
root@3be8ac8498a7:/# exit
exit

# Kill the only one process, container stopped and restart automatically because restart policy is unless-stopped
isaac@isaac-KVM:~$ docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
3be8ac8498a7        ubuntu              "/bin/bash"         19 seconds ago      Up 7 seconds                            nostalgic_gagarin

# Use command to stop a container
isaac@isaac-KVM:~$ docker container stop 3be8ac8498a7
3be8ac8498a7
isaac@isaac-KVM:~$ docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

# Container is not started after docker restart because restart policy is unless-stopped
isaac@isaac-KVM:~$ sudo service docker restart
isaac@isaac-KVM:~$ docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
isaac@isaac-KVM:~$



on-failure
  1. Restart container when it's stopped with non-zero exit code
  2. Restart container when docker restart

Docker - container - start and stop container


  • Run a container
  • Ex. docker container run <image> <app>
  • Ex. docker container run -it ubuntu /bin/bash
  • -it will connect to current terminal
  • Stop container: docker container stop
  • Start container: docker container start
# Originally there are 8 containers
isaac@isaac-KVM:~$ docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                        PORTS               NAMES
71c2bac3e63f        ubuntu              "/bin/bash"              2 minutes ago       Exited (127) 30 seconds ago                       dreamy_neumann
5a6744d26f4d        ubuntu              "/bin/sh"                3 minutes ago       Exited (0) 2 minutes ago                          nostalgic_swanson
0f0ddaa9c4f4        nginx               "nginx -g 'daemon of…"   3 minutes ago       Exited (0) 3 minutes ago                          cranky_turing
5a8dfb31e1b5        nginx               "nginx -g 'daemon of…"   4 minutes ago       Exited (0) 4 minutes ago                          quirky_newton
20a69a2f40b0        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                           sharp_zhukovsky
28a62f8da2d0        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                           affectionate_curran
4df4b2d4c69e        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                           gracious_jones
81977c50304b        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                           cocky_poincare
isaac@isaac-KVM:~$

# Start new container
isaac@isaac-KVM:~$ docker container run -it ubuntu /bin/bash
root@1bbcd62b047b:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@1bbcd62b047b:/# exit
exit

# Now there are 9 containers
isaac@isaac-KVM:~$ docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                            PORTS               NAMES
1bbcd62b047b        ubuntu              "/bin/bash"              9 seconds ago       Exited (0) 4 seconds ago                              blissful_turing
71c2bac3e63f        ubuntu              "/bin/bash"              2 minutes ago       Exited (127) About a minute ago                       dreamy_neumann
5a6744d26f4d        ubuntu              "/bin/sh"                3 minutes ago       Exited (0) 3 minutes ago                              nostalgic_swanson
0f0ddaa9c4f4        nginx               "nginx -g 'daemon of…"   4 minutes ago       Exited (0) 4 minutes ago                              cranky_turing
5a8dfb31e1b5        nginx               "nginx -g 'daemon of…"   5 minutes ago       Exited (0) 5 minutes ago                              quirky_newton
20a69a2f40b0        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                               sharp_zhukovsky
28a62f8da2d0        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                               affectionate_curran
4df4b2d4c69e        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                               gracious_jones
81977c50304b        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                               cocky_poincare

# No container alive, because the latest process was killed by exit
isaac@isaac-KVM:~$ docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
isaac@isaac-KVM:~$

  • Del container: docker container rm
isaac@isaac-KVM:~$ docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                        PORTS               NAMES
1bbcd62b047b        ubuntu              "/bin/bash"              11 minutes ago      Exited (0) 11 minutes ago                         blissful_turing
71c2bac3e63f        ubuntu              "/bin/bash"              14 minutes ago      Exited (127) 12 minutes ago                       dreamy_neumann
5a6744d26f4d        ubuntu              "/bin/sh"                15 minutes ago      Exited (0) 15 minutes ago                         nostalgic_swanson
0f0ddaa9c4f4        nginx               "nginx -g 'daemon of…"   15 minutes ago      Exited (0) 15 minutes ago                         cranky_turing
5a8dfb31e1b5        nginx               "nginx -g 'daemon of…"   17 minutes ago      Exited (0) 16 minutes ago                         quirky_newton
20a69a2f40b0        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                           sharp_zhukovsky
28a62f8da2d0        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                           affectionate_curran
4df4b2d4c69e        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                           gracious_jones
81977c50304b        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                           cocky_poincare

isaac@isaac-KVM:~$ docker container rm 81977c50304b
81977c50304b


isaac@isaac-KVM:~$ docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                        PORTS               NAMES
1bbcd62b047b        ubuntu              "/bin/bash"              12 minutes ago      Exited (0) 11 minutes ago                         blissful_turing
71c2bac3e63f        ubuntu              "/bin/bash"              14 minutes ago      Exited (127) 13 minutes ago                       dreamy_neumann
5a6744d26f4d        ubuntu              "/bin/sh"                15 minutes ago      Exited (0) 15 minutes ago                         nostalgic_swanson
0f0ddaa9c4f4        nginx               "nginx -g 'daemon of…"   16 minutes ago      Exited (0) 15 minutes ago                         cranky_turing
5a8dfb31e1b5        nginx               "nginx -g 'daemon of…"   17 minutes ago      Exited (0) 17 minutes ago                         quirky_newton
20a69a2f40b0        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                           sharp_zhukovsky
28a62f8da2d0        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                           affectionate_curran
4df4b2d4c69e        ubuntu:latest       "/bin/bash"              2 months ago        Exited (0) 2 months ago                           gracious_jones
isaac@isaac-KVM:~$
  • Kill the only one process in container also kill the container
  • Ctrl - PQ: exit container without terminating it
  • Ex. Reattach to container terminal docker container exec -it {containerid} bash 
  • After reattach terminal and execute ps command, will see 2 processes. Because docker container exec command create new one, means exit this time will not kill container
# There is no container
dockeruser@isaac-KVM:~$ docker container ls -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

# After run, one bash process in container
dockeruser@isaac-KVM:~$ docker container run -it ubuntu /bin/bash
root@1653d3c07542:/# ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  6.2  0.0  18504  3452 pts/0    Ss   17:33   0:00 /bin/bash
root        11  0.0  0.0  34396  2856 pts/0    R+   17:33   0:00 ps aux

# Ctrl + PQ to exit terminal
root@1653d3c07542:/# dockeruser@isaac-KVM:~$ docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
1653d3c07542        ubuntu              "/bin/bash"         28 seconds ago      Up 27 seconds                           flamboyant_ganguly

# Reattach container
dockeruser@isaac-KVM:~$ docker container exec -it 1653d3c07542 bash

# Find there are 2 processes
root@1653d3c07542:/# ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.2  0.0  18504  3452 pts/0    Ss+  17:33   0:00 /bin/bash
root        12  5.5  0.0  18504  3428 pts/1    Ss   17:34   0:00 bash
root        21  0.0  0.0  34396  2868 pts/1    R+   17:34   0:00 ps aux

# So container will not terminate because there are more than one process
root@1653d3c07542:/# exit
exit
dockeruser@isaac-KVM:~$ docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
1653d3c07542        ubuntu              "/bin/bash"         2 minutes ago       Up 2 minutes                            flamboyant_ganguly
dockeruser@isaac-KVM:~$
  • Delete container
  • 1. docker container stop {name}
  • 2. docker container rm {name}
  • Or: docker container rm {name} -f

  • Ex. Check docker is running: docker version
isaac@isaac-KVM:~$ docker version
Client:
Version:           18.09.7
API version:       1.39
Go version:        go1.10.4
Git commit:        2d0083d
Built:             Wed Jul  3 12:13:54 2019
OS/Arch:           linux/amd64
Experimental:      false


Server:
Engine:
  Version:          18.09.7
  API version:      1.39 (minimum version 1.12)
  Go version:       go1.10.4
  Git commit:       2d0083d
  Built:            Mon Jul  1 19:14:14 2019
  OS/Arch:          linux/amd64
  Experimental:     false
  • Need make sure username is in docker user group
  • Add to usergroup if it is not: usermod -aG docker <user>
# add user
isaac@isaac-KVM:~$ sudo adduser dockeruser
[sudo] password for isaac:
Adding user `dockeruser' ...
Adding new group `dockeruser' (1001) ...
Adding new user `dockeruser' (1001) with group `dockeruser' ...
Creating home directory `/home/dockeruser' ...
Copying files from `/etc/skel' ...
New password:
Retype new password:
passwd: password updated successfully
Changing the user information for dockeruser
Enter the new value, or press ENTER for the default
        Full Name []:
        Room Number []:
        Work Phone []:
        Home Phone []:
        Other []:
Is the information correct? [Y/n]
isaac@isaac-KVM:~$

# change to dockeruser, but unable to execute docker version
isaac@isaac-KVM:~$ su - dockeruser
Password:
dockeruser@isaac-KVM:~$ docker version
Client:
Version:           18.09.7
API version:       1.39
Go version:        go1.10.4
Git commit:        2d0083d
Built:             Wed Jul  3 12:13:54 2019
OS/Arch:           linux/amd64
Experimental:      false
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.39/version: dial unix /var/run/docker.sock: connect: permission denied
dockeruser@isaac-KVM:~$

# it's because not in docker group, so need add to docker group (Notice this action need to be did by sudouser)
dockeruser@isaac-KVM:~$ usermod -aG docker dockeruser
usermod: Permission denied.
usermod: cannot lock /etc/passwd; try again later.
dockeruser@isaac-KVM:~$ sudo usermod -aG docker dockeruser
[sudo] password for dockeruser:
dockeruser is not in the sudoers file.  This incident will be reported.
dockeruser@isaac-KVM:~$ su - isaac
Password:
isaac@isaac-KVM:~$ usermod -aG docker dockeruser
usermod: Permission denied.
usermod: cannot lock /etc/passwd; try again later.
isaac@isaac-KVM:~$ sudo usermod -aG docker dockeruser

# after add to docker user group, dockeruser can use docker version
isaac@isaac-KVM:~$ su - dockeruser
Password:
dockeruser@isaac-KVM:~$ docker version
Client:
Version:           18.09.7
API version:       1.39
Go version:        go1.10.4
Git commit:        2d0083d
Built:             Wed Jul  3 12:13:54 2019
OS/Arch:           linux/amd64
Experimental:      false


Server:
Engine:
  Version:          18.09.7
  API version:      1.39 (minimum version 1.12)
  Go version:       go1.10.4
  Git commit:       2d0083d
  Built:            Mon Jul  1 19:14:14 2019
  OS/Arch:          linux/amd64
  Experimental:     false
dockeruser@isaac-KVM:~$




別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...