<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lim Yee Jie on Medium]]></title>
        <description><![CDATA[Stories by Lim Yee Jie on Medium]]></description>
        <link>https://medium.com/@jielim36?source=rss-5c85604199dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DD_-q0VgXQ7JronW0PJ32A.jpeg</url>
            <title>Stories by Lim Yee Jie on Medium</title>
            <link>https://medium.com/@jielim36?source=rss-5c85604199dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 14:00:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jielim36/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What is gRPC? (Go Example)]]></title>
            <link>https://medium.com/@jielim36/what-is-grpc-go-example-7c2eba432414?source=rss-5c85604199dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c2eba432414</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Lim Yee Jie]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 13:02:05 GMT</pubDate>
            <atom:updated>2024-10-09T13:02:05.439Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is gRPC?</h3><p>gRPC is a modern open source high performance Remote Procedure Call (RPC) framework that <strong>can run in any environment.</strong></p><p><strong>Summary of gRPC:</strong> It’s like internal function calls, but extended to allow remote function calls between different applications or services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*JjK8646c3neCWVqf" /></figure><h3>Key Features</h3><ul><li><strong>Cross-language support</strong>: Allows communication between different programming languages (e.g., Go service talking to Python service).</li><li><strong>Efficient serialization</strong>: Uses Protocol Buffers (Protobuf) for fast and compact data serialization.</li><li><strong>Bi-directional streaming</strong>: Supports real-time communication between client and server (data flows both ways simultaneously).</li><li><strong>Load balancing and fault tolerance</strong>: Has built-in features for managing traffic and handling failures.</li></ul><h3>Use Cases</h3><ul><li><strong>Microservices communication</strong>: Ideal for scalable and efficient communication between microservices.</li><li><strong>Mobile and web applications</strong>: Used in apps that require fast, low-latency communication (e.g., real-time chat, video streaming).</li><li><strong>APIs</strong>: For creating efficient, cross-platform APIs (alternative to REST or GraphQL).</li></ul><h3>Compare with another RPC</h3><p>Compared to other RPC frameworks, gRPC has the following distinct advantages:</p><p><strong>High performance</strong>:</p><ul><li>gRPC uses <strong>Protocol Buffers (Protobuf)</strong> for data serialization, which is fast and produces compact data, far superior to text-based serialization formats like JSON and XML.</li><li>It supports <strong>HTTP/2</strong>, improving transmission efficiency and performance, with support for multiplexing, streaming data, and header compression.</li></ul><p><strong>Multi-language support</strong>:</p><ul><li>gRPC natively supports multiple programming languages, including Go, Java, Python, C++, etc., making it suitable for cross-language system development.</li></ul><h3>Golang Demonstration</h3><h3>Prerequisites:</h3><ul><li>Go Environment</li><li>Protocol Buffer Compiler: <a href="https://grpc.io/docs/protoc-installation/">https://grpc.io/docs/protoc-installation/</a></li><li>Go plugins for the protocol Compiler:</li></ul><pre># Install the protocol compiler plugins for Go<br>$ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest<br>$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest</pre><h3>Step 1: Initialize Golang gRPC Services</h3><p>Root Folder: grpg-golang , created two services service-a and service-b under the root folder.</p><pre># under path gRPC-golang/service-a:<br>$ go mod init grpg-service-a<br>$ go get -u google.golang.org/grpc<br><br># under path gRPC-golang/service-b:<br>$ go mod init grpg-service-a<br>$ go get -u google.golang.org/grpc</pre><h3>Step 2: Create a proto file (protocol buffer) for defining gRPC API</h3><h3>Protocol Buffer File Explanation</h3><p>This is a standardized way of defining the API for different services/applications. Once defined, you can use the Protocol Buffers compiler to generate code based on the .proto file in your chosen language.</p><pre>service-a (root):<br>-go.mod<br>-go.sum<br>-main.go<br>-rpc<br>--service-a.proto # create a proto file</pre><p>service-a.proto : Defining your gRPC Remote API here</p><pre>syntax = &quot;proto3&quot;;<br><br>package main;<br><br>option go_package = &quot;/rpc;rpc&quot;;<br>pr<br>service ServiceA {<br>    // defining your API here<br>    rpc GetServiceA_API (HelloRequest) returns (HelloResponse);<br>}<br><br>// defining your request and response template here<br>message HelloRequest {<br>    int64 id = 1;<br>    string username = 2;<br>    string address = 3;<br>}<br><br>message HelloResponse {<br>    string data = 1;<br>}</pre><h3>Step 3: Generating Server Code</h3><p>Generate the gRPC server interface from our .proto service definition. From the service-a root path, run the following command:</p><pre>$ protoc --go_out=. --go-grpc_out=. rpc/service-a.proto</pre><p>After that, you can see the system will be automatic generate two files which are: xx_grpc.pb.go and xx.pb.go .</p><pre>service-a (root):<br>-go.mod<br>-go.sum<br>-main.go<br>-rpc<br>--service-a.proto # create a proto file<br>--service-a_grpc.pb.go<br>--service-a.pb.go</pre><h3>Step 4: Implement the API Service from the gRPC (proto file)</h3><p>Paste this code to your service-a/main.go :</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> pb &quot;grpg-service-a/rpc&quot; // generate code&#39;s path<br> &quot;log&quot;<br> &quot;net&quot;<br> &quot;google.golang.org/grpc&quot;<br>)<br><br>type ServiceA_Server struct {<br> pb.UnimplementedServiceAServer<br>}<br><br>// function name must be same with the Defined APi Function on proto file<br>// you are able to put the Request Template that you defined as function&#39;s params type<br>// you are able to put the Response Template that you defined as function&#39;s response type<br>func (s *ServiceA_Server) GetServiceA_API(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error){<br> // code...<br> return &amp;pb.HelloResponse{<br>  Data: &quot;This is a Response Data&quot;,<br> }, nil<br>}<br><br>func main(){<br> listening, err := net.Listen(&quot;tcp&quot;,&quot;:50051&quot;)<br> if err != nil {<br>  log.Fatalf(&quot;Failed to listen: %v&quot;, err)<br> }<br> grpcServer := grpc.NewServer()<br> pb.RegisterServiceAServer(grpcServer, &amp;ServiceA_Server{})<br> log.Println(&quot;gRPC server is running on port 50051&quot;)<br> if err := grpcServer.Serve(listening); err != nil {<br>        log.Fatalf(&quot;failed to serve: %v&quot;, err)<br>    }<br>}</pre><h3>Step 5: Repeat the similar step to Service B (Client Side)</h3><ol><li>Copy the proto file from service-a to service-b .</li><li>Run the command: protoc --go_out=. --go-grpc_out=. rpc/service-a.proto on service-b root path.</li><li>Create main.go file on your service-b root path</li></ol><pre>// Current Path:<br>service-b (root):<br>-go.mod<br>-go.sum<br>-main.go # Different from Service A<br>-rpc<br>--service-a.proto # using the same proto file from service a<br>--service-a_grpc.pb.go # and generate again<br>--service-a.pb.go # generate again</pre><p>Paste this code to your service-b/main.go :</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> pb &quot;grpc-service-b/rpc&quot;<br> &quot;log&quot;<br> &quot;time&quot;<br> &quot;google.golang.org/grpc&quot;<br>)<br><br>func main() {<br> ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)<br> defer cancel()<br> conn, err := grpc.DialContext(ctx, &quot;localhost:50051&quot;, grpc.WithInsecure())<br> if err != nil {<br>  log.Fatalf(&quot;Did not connect: %v&quot;, err)<br> }<br> defer conn.Close()<br> client := pb.NewServiceAClient(conn)<br> req := &amp;pb.HelloRequest{<br>  Id: 999,<br>  Username: &quot;Jielim36_Author&quot;,<br>  Address: &quot;AddressXXX&quot;,<br> }<br> // Called the function at here<br> res, err := client.GetServiceA_API(ctx, req)<br> if err != nil {<br>  log.Fatalf(&quot;Error calling HelloAPI: %v&quot;, err)<br> }<br> // Print the response<br> fmt.Printf(&quot;Response from server: %s\\n&quot;, res.Data)<br>}</pre><h3>Step 6: Run Services</h3><pre># Under service-a root path, run the following command:<br>$ go run main.go<br><br># Under service-b root path, run the following command:<br>$ go run main.go<br># After you run service-b&#39;s main.go, it will be output the result:<br>&quot;Response from server: This is a Response Data&quot;</pre><h3>Noted:</h3><p>Each gRPC service is <strong>not limited to a single responsibility</strong> (acting solely as a server or client); rather, it <strong>can function as both the server side and the client side</strong>, <strong>allowing the service to send and receive data within the same application/service</strong>. This bidirectional communication capability enables services to flexibly handle complex interaction scenarios, enhancing the system’s scalability and efficiency.</p><p>(Summary: service-a can be build grpc api, also can send the grpc request to another grpc service such as service-b)</p><h3>How to read gRPC source code quickly even without learning</h3><ol><li>Find the .proto file to check all existing gRPC API.</li></ol><pre>syntax = &quot;proto3&quot;;<br><br>package main;<br><br>option go_package = &quot;/rpc;rpc&quot;;<br><br>// All of the gRPC API list at here<br>service ServiceA {<br>  // syntax: rpc &lt;API_Name&gt; (&lt;Request_Body&gt;) returns (&lt;Response_Body&gt;)<br>    rpc GetServiceA_API (HelloRequest) returns (HelloResponse);<br>}<br><br>// All request body and response body list here.<br>message HelloRequest {<br>    int64 id = 1;<br>    string username = 2;<br>    string address = 3;<br>}<br><br>message HelloResponse {<br>    string data = 1;<br>}</pre><ol><li>Find the code grpc.Dial() to find the server side and implemented gRPC API function.</li><li>Find the .&lt;API_Name&gt; on your client side. (You should determine which service is the client side first).</li></ol><h3>Enhancement Structure</h3><h3>Solution 1: Seperate to independent folder</h3><p>Since we copy the same .proto file in service-a and service-b folder. We can try to seperate to a independent folder</p><pre>grpc-project/<br>│<br>├── proto/                       # Directory for .proto files (gRPC service definitions)<br>│   └── service.proto             # Define the gRPC service and messages here<br>│<br>├── client/                      # Client implementation<br>│   ├── client.go                 # gRPC client implementation in Go (or other language)<br>│   └── client_test.go            # Unit tests for the client<br>│<br>├── server/                      # Server implementation<br>│   ├── server.go                 # gRPC server implementation in Go (or other language)<br>│   └── server_test.go            # Unit tests for the server<br>│<br>├── pb/                          # Generated Protocol Buffers (protobuf) code<br>│   ├── service.pb.go             # Auto-generated Go code from service.proto<br>│   ├── service.pb.py             # Auto-generated Python code (if using Python)<br>│   ├── service_grpc.pb.go        # Auto-generated Go code for gRPC client and server stubs<br>│   └── service_grpc.pb.py        # Auto-generated Python code (if using Python)<br>│<br>├── scripts/                     # Utility scripts for building, running, etc.<br>│   └── generate_proto.sh         # Script to generate protobuf and gRPC code from .proto files<br>│<br>├── Dockerfile                   # Dockerfile for containerizing the service (optional)<br>├── Makefile                     # Build automation (optional)<br>├── go.mod                       # Go module file (for Go projects)<br>├── README.md                    # Project documentation<br>└── .gitignore                   # Ignored files</pre><h3>Solution 2: Fetch the Proto File from Server Side</h3><p>When you want to call the gRPC API in your client side. Trying to import the .proto file from server side.</p><pre># Example in Service-B (Client Side)<br>import (<br>	rpc &quot;github.com/grpc-service-a/rpc&quot; # import the rpc package from service-a<br>)<br><br>// code...<br><br>// example:<br>// use &quot;rpc&quot; to access to objects you defined on .proto file in service-a<br>func (s *MyService) GetUsers(user rpc.User) {<br> // code for send gRPC request to server side...<br>}</pre><p>Details refer to: <a href="https://medium.com/@nate510/structuring-go-grpc-microservices-dd176fdf28d0">https://medium.com/@nate510/structuring-go-grpc-microservices-dd176fdf28d0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c2eba432414" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Docker Compose and Build a Redis Cluster with Docker Compose]]></title>
            <link>https://medium.com/@jielim36/basic-docker-compose-and-build-a-redis-cluster-with-docker-compose-0313f063afb6?source=rss-5c85604199dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/0313f063afb6</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Lim Yee Jie]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 14:02:28 GMT</pubDate>
            <atom:updated>2024-01-23T14:02:28.472Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker Compose</h3><p>As demonstrated in the Redis Cluster example above, we need to create numerous containers and manage aspects such as networking and data volumes for these containers. Handling these tasks one by one with individual Docker commands can be cumbersome. Therefore, Docker Compose can address this issue.</p><p>Docker Compose can be used to define and run multiple containers, configuring the services of an application through a YAML file. Subsequently, a single command can be used to create and start all services based on the configuration.</p><p><strong>Create a yaml file</strong><br>Command: $ nano docker-compose.yaml</p><pre># docker-compose.yml<br>services:<br>    test:<br>        image: redis</pre><p><strong>Usage</strong></p><pre># Under your docker compose file&#39;s path<br>$ docker compose up # Execute (similar with docker run -it)<br>$ docker compose up -d  # Execute the container in background (similar with docker run -d)<br># If your docker compose yaml file name is not called &quot;docker-compose.yaml&quot;<br>$ docker-compose -f /path/to/your/project/your-custom-name.yml up -d<br><br><br># Check container<br>$ docker ps<br>CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS      NAMES<br>4035917143c5   redis     &quot;docker-entrypoint.s…&quot;   4 minutes ago   Up 3 minutes   6379/tcp   docker-compose-testing-test-1</pre><p><strong>Docker compose yaml details:</strong></p><p>Reference: <a href="https://docs.docker.com/compose/compose-file/">https://docs.docker.com/compose/compose-file/</a></p><p>Top level:</p><ol><li>services: Configuration of the container, you can think that it is similar with the docker run command.</li><li>networks: Custom Network Manage.create the custom network, and the services side can reference this network configuration, it can be used with several services at the same time.</li><li>volumes: Managing volumes. Can be used with several services at the same time.</li><li>version: Docker compose version.</li></ol><pre>#top level:<br>version: &quot;2.21&quot;<br>services:<br>    nginx-demo:     # service name (create a container), it&#39;s not a container name<br>        container_name: nginx-1<br>        image: nginx    # image name<br>        restart: always     # optional: restart strategy<br>        networks:   # reference with networks top level<br>            - my-frontend-network  # you can call/reference the custom network<br>        volumes:    # reference with volumes top level<br>            - nginx_volume:/usr/share/nginx/html  # call the specific volume<br>        environment:<br>            APP_ENV: dev<br>        dns: 8.8.8.8<br>        depends_on:<br>            - db    # Build this container (nginx) after the container in db section created<br>        ports:<br>            - 8000:80<br><br>    # other service (create other container)<br>    db:<br>        image: mysql<br>        container_name: mysql-1<br>        volumes:<br>            - db_volume:/var/lib/mysql<br>        networks:<br>            - my-frontend-network<br>        environment:<br>            MYSQL_ROOT_PASSWORD: 123456<br>        ports: 33060:3306<br><br><br>networks:   # top level<br>    my-frontend-network:     # name of network for services side reference it<br>        name: app-network   # name of customer network<br>        driver: bridge<br>        ipam:<br>            driver: default<br>            config:<br>                - subnet: 172.28.0.0/16<br>                  ip_range: 172.28.5.0/24<br>                  gateway: 172.28.5.254<br>                  aux_addresses:<br>                    host1: 172.28.1.5<br>                    host2: 172.28.1.6<br>                    host3: 172.28.1.7<br>            options:<br>                foo: bar<br>                bax: &quot;0&quot;<br><br>volumes:  # top level<br>    db_volume:<br>        name: &quot;mysql-volume&quot;<br>    nginx_volume:<br>        name: &quot;nginx-volume&quot;</pre><p><strong>Docker compose command:</strong><br>There are many command similar with docker.</p><pre>Options:<br>      --ansi string                Control when to print ANSI control characters<br>                                   (&quot;never&quot;|&quot;always&quot;|&quot;auto&quot;) (default &quot;auto&quot;)<br>      --compatibility              Run compose in backward compatibility mode<br>      --dry-run                    Execute command in dry run mode<br>      --env-file stringArray       Specify an alternate environment file.<br>  -f, --file stringArray           Compose configuration files<br>      --parallel int               Control max parallelism, -1 for unlimited (default -1)<br>      --profile stringArray        Specify a profile to enable<br>      --progress string            Set type of progress output (auto, tty, plain, quiet) (default &quot;auto&quot;)<br>      --project-directory string   Specify an alternate working directory<br>                                   (default: the path of the, first specified, Compose file)<br>  -p, --project-name string        Project name<br><br>Commands:<br>  build       Build or rebuild services<br>  config      Parse, resolve and render compose file in canonical format<br>  cp          Copy files/folders between a service container and the local filesystem<br>  create      Creates containers for a service.<br>  down        Stop and remove containers, networks<br>  events      Receive real time events from containers.<br>  exec        Execute a command in a running container.<br>  images      List images used by the created containers<br>  kill        Force stop service containers.<br>  logs        View output from containers<br>  ls          List running compose projects<br>  pause       Pause services<br>  port        Print the public port for a port binding.<br>  ps          List containers<br>  pull        Pull service images<br>  push        Push service images<br>  restart     Restart service containers<br>  rm          Removes stopped service containers<br>  run         Run a one-off command on a service.<br>  start       Start services<br>  stop        Stop services<br>  top         Display the running processes<br>  unpause     Unpause services<br>  up          Create and start containers<br>  version     Show the Docker Compose version information<br>  wait        Block until the first service container stops</pre><ol><li>docker compose config: Parse, resolve and render compose file in canonical format</li></ol><pre># it can check your docker-compose.yml file is correct or not<br>$ docker compose config<br>ERROR: In file &#39;./docker-compose.yml&#39;, volume &#39;db_volume&#39; must be a mapping not an array.<br><br># Successful Case:<br>$ docker compose config # if no error, return back the details information<br>name: docker-compose-testing<br>services:<br>  db:<br>    ...<br>  nginx-demo:<br>    ...<br>    volumes:    # in config will show some details information<br>    - type: volume<br>      source: nginx_volume<br>      target: /usr/share/nginx/html<br>      volume: {}<br>networks:<br>    ...<br><br>volumes:<br>  ...</pre><p>2. docker compose create &lt;service_name&gt;: docker-compose.yaml file can create many images at the same time, but you can using this command to create a specific image and run container.</p><pre>$ docker compose create db # create mysql<br>[+] Creating 2/0<br> ✔ Volume &quot;mysql-volume&quot;  Created                                                                        0.0s<br> ✔ Container mysql-1      Created</pre><p>3. docker compose up: create and run all service (container)</p><pre>$ docker compose up -d  # -d option: run in background<br>[+] Running 3/3<br> ✔ Network app-network  Created                                                                                                            0.1s<br> ✔ Container mysql-1    Started                                                                                                            0.0s<br> ✔ Container nginx-1    Started</pre><p>4. docker compose ps: check the running compose container</p><pre>$ docker compose ps<br>NAME      IMAGE     COMMAND                                          SERVICE      CREATED         STATUS         PORTS<br>mysql-1   mysql     &quot;docker-entrypoint.sh mysqld&quot;                    db           8 minutes ago   Up 8 minutes   33060/tcp, 0.0.0.0:33060-&gt;3306/tcp, :::33060-&gt;3306/tcp<br>nginx-1   nginx     &quot;/docker-entrypoint.sh nginx -g &#39;daemon off;&#39;&quot;   nginx-demo   8 minutes ago   Up 8 minutes   0.0.0.0:8000-&gt;80/tcp, :::8000-&gt;80/tcp</pre><p>5. docker compose down: Deleted anythings created by this docker compose</p><pre>$ docker compose down<br>[+] Running 3/3<br> ✔ Container mysql-1                       Removed                                                       0.0s<br> ✔ Network docker-compose-testing_default  Removed                                                       0.6s<br> ✔ Network app-network                     Removed</pre><p>6. docker compose images</p><pre>$ docker compose images<br>CONTAINER           REPOSITORY          TAG                 IMAGE ID            SIZE<br>mysql-1             mysql               latest              73246731c4b0        619MB<br># Successful<br><br>$ docker compose ps -a<br>NAME      IMAGE     COMMAND                         SERVICE   CREATED         STATUS    PORTS<br>mysql-1   mysql     &quot;docker-entrypoint.sh mysqld&quot;   db        2 minutes ago   Created</pre><h3>Build a Redis Cluster with Docker Compose</h3><p>Create volume (mount) file first:</p><pre># run this for loop to create each redis container configuration file<br>for port in $(seq 1 6); do<br>  mkdir -p /redis/node-${port}/conf<br>  touch /redis/node-${port}/conf/redis.conf<br>  cat &lt;&lt; EOF &gt;/redis/node-${port}/conf/redis.conf<br>port 6379<br>bind 0.0.0.0<br>cluster-enabled yes<br>cluster-config-file nodes.conf<br>cluster-node-timeout 5000<br>cluster-announce-ip 172.38.0.1${port}<br>cluster-announce-port 6379<br>cluster-announce-bus-port 16379<br>appendonly yes<br>EOF<br>done</pre><p>Write the docker-compose.yaml file:</p><pre>version: &quot;3&quot;<br>services:<br>    redis-1:<br>        image: redis<br>        command: [&quot;redis-server&quot;,&quot;/etc/redis/redis.conf&quot;]<br>        volumes:<br>            - /redis/node-1/data:/data<br>            - /redis/node-1/conf/redis.conf:/etc/redis/redis.conf<br>        ports:<br>            - 6371:6379<br>            - 16371:16379<br>        networks:<br>            redis_network:<br>                ipv4_address: 172.38.0.11<br>    redis-2:<br>        image: redis<br>        command: [&quot;redis-server&quot;, &quot;/etc/redis/redis.conf&quot;]<br>        volumes:<br>            - /redis/node-2/data:/data<br>            - /redis/node-2/conf/redis.conf:/etc/redis/redis.conf<br>        ports:<br>            - &quot;6372:6379&quot;<br>            - 16372:16379<br>        networks:<br>            redis_network:<br>                ipv4_address: 172.38.0.12<br>    redis-3:<br>        image: redis<br>        command: [&quot;redis-server&quot;, &quot;/etc/redis/redis.conf&quot;]<br>        volumes:<br>            - /redis/node-3/data:/data<br>            - /redis/node-3/conf/redis.conf:/etc/redis/redis.conf<br>        ports:<br>            - &quot;6373:6379&quot;<br>            - 16373:16379<br>        networks:<br>            redis_network:<br>                ipv4_address: 172.38.0.13<br>    redis-4:<br>        image: redis<br>        command: [&quot;redis-server&quot;, &quot;/etc/redis/redis.conf&quot;]<br>        volumes:<br>            - /redis/node-4/data:/data<br>            - /redis/node-4/conf/redis.conf:/etc/redis/redis.conf<br>        ports:<br>            - &quot;6374:6379&quot;<br>            - 16374:16379<br>        networks:<br>            redis_network:<br>                ipv4_address: 172.38.0.14<br>    redis-5:<br>        image: redis<br>        command: [&quot;redis-server&quot;, &quot;/etc/redis/redis.conf&quot;]<br>        volumes:<br>            - /redis/node-5/data:/data<br>            - /redis/node-5/conf/redis.conf:/etc/redis/redis.conf<br>        ports:<br>            - &quot;6375:6379&quot;<br>            - 16375:16379<br>        networks:<br>            redis_network:<br>                ipv4_address: 172.38.0.15<br>    redis-6:<br>        image: redis<br>        command: [&quot;redis-server&quot;, &quot;/etc/redis/redis.conf&quot;]<br>        volumes:<br>            - /redis/node-6/data:/data<br>            - /redis/node-6/conf/redis.conf:/etc/redis/redis.conf<br>        ports:<br>            - &quot;6376:6379&quot;<br>            - &quot;16376:16379&quot;<br>        networks:<br>            redis_network:<br>                ipv4_address: 172.38.0.16<br>networks:<br>    redis_network:<br>        driver: bridge<br>        ipam:<br>            config:<br>                - subnet: 172.38.0.0/16<br>                  gateway: 172.38.0.1</pre><p>Command:</p><pre># check docker-compose.yaml is correct or not<br>$ docker compose config<br><br># Run docker compose<br>root@jielim36:/home/jielim36/redis-cluster-docker-compose# docker compose up -d<br>[+] Running 7/7<br> ✔ Network redis-cluster-docker-compose_redis_network  Created                                                                             0.1s<br> ✔ Container redis-cluster-docker-compose-redis-4-1    Started                                                                             0.1s<br> ✔ Container redis-cluster-docker-compose-redis-3-1    Started                                                                             0.1s<br> ✔ Container redis-cluster-docker-compose-redis-5-1    Started                                                                             0.1s<br> ✔ Container redis-cluster-docker-compose-redis-1-1    Started                                                                             0.1s<br> ✔ Container redis-cluster-docker-compose-redis-6-1    Started                                                                             0.1s<br> ✔ Container redis-cluster-docker-compose-redis-2-1    Started                                                                             0.1s<br><br># check running container<br>$ docker compose ps<br>NAME                                     IMAGE     COMMAND                                                     SERVICE   CREATED          STATUS          PORTS<br>redis-cluster-docker-compose-redis-1-1   redis     &quot;docker-entrypoint.sh redis-server /etc/redis/redis.conf&quot;   redis-1   23 seconds ago   Up 20 seconds   0.0.0.0:6371-&gt;6379/tcp, :::6371-&gt;6379/tcp, 0.0.0.0:16371-&gt;16379/tcp, :::16371-&gt;16379/tcp<br>redis-cluster-docker-compose-redis-2-1   redis     &quot;docker-entrypoint.sh redis-server /etc/redis/redis.conf&quot;   redis-2   23 seconds ago   Up 20 seconds   0.0.0.0:6372-&gt;6379/tcp, :::6372-&gt;6379/tcp, 0.0.0.0:16372-&gt;16379/tcp, :::16372-&gt;16379/tcp<br>redis-cluster-docker-compose-redis-3-1   redis     &quot;docker-entrypoint.sh redis-server /etc/redis/redis.conf&quot;   redis-3   23 seconds ago   Up 20 seconds   0.0.0.0:6373-&gt;6379/tcp, :::6373-&gt;6379/tcp, 0.0.0.0:16373-&gt;16379/tcp, :::16373-&gt;16379/tcp<br>redis-cluster-docker-compose-redis-4-1   redis     &quot;docker-entrypoint.sh redis-server /etc/redis/redis.conf&quot;   redis-4   23 seconds ago   Up 20 seconds   0.0.0.0:6374-&gt;6379/tcp, :::6374-&gt;6379/tcp, 0.0.0.0:16374-&gt;16379/tcp, :::16374-&gt;16379/tcp<br>redis-cluster-docker-compose-redis-5-1   redis     &quot;docker-entrypoint.sh redis-server /etc/redis/redis.conf&quot;   redis-5   23 seconds ago   Up 20 seconds   0.0.0.0:6375-&gt;6379/tcp, :::6375-&gt;6379/tcp, 0.0.0.0:16375-&gt;16379/tcp, :::16375-&gt;16379/tcp<br>redis-cluster-docker-compose-redis-6-1   redis     &quot;docker-entrypoint.sh redis-server /etc/redis/redis.conf&quot;   redis-6   23 seconds ago   Up 20 seconds   0.0.0.0:6376-&gt;6379/tcp, :::6376-&gt;6379/tcp, 0.0.0.0:16376-&gt;16379/tcp, :::16376-&gt;16379/tcp<br><br># If created successful, enter to the redis-1 to create cluster<br>$ redis-cli --cluster create 172.38.0.11:6379 172.38.0.12:6379 172.38.0.13:6379 172.38.0.14:6379 172.38.0.15:6379 172.38.0.16:6379 --cluster-replicas 1<br><br># Check again, enter to the redis-cli with cluster<br>root@b59ad0535541:/data$ redis-cli -c<br># check the relationship of all redis nodes<br>127.0.0.1:6379&gt; cluster nodes<br>94cce23d515a45ca974016bebf8354c939cd686b 172.38.0.11:6379@16379 myself,master - 0 1705657020000 1 connected 0-5460<br>2ddaeb2cbce78eee11d02de916ef87ed9cd02a1a 172.38.0.12:6379@16379 master - 0 1705657020000 2 connected 5461-10922<br>c77d4c93aa9ee2abb593abacfd9cfd7a5caae0df 172.38.0.13:6379@16379 master - 0 1705657021585 3 connected 10923-16383<br>af8f4638ff90e4aa04797a0cb6fa6a517ed041d4 172.38.0.15:6379@16379 slave 94cce23d515a45ca974016bebf8354c939cd686b 0 1705657021585 1 connected<br>18c33a87f82726cbc77cf67f7a72fdd6ecc15dda 172.38.0.16:6379@16379 slave 2ddaeb2cbce78eee11d02de916ef87ed9cd02a1a 0 1705657020000 2 connected<br>2fb725e35588b2edc34d8d3bc09d85593f2fd963 172.38.0.14:6379@16379 slave c77d4c93aa9ee2abb593abacfd9cfd7a5caae0df 0 1705657021000 3 connected</pre><p>Command: $ redis-cli --cluster create 172.38.0.11:6379 172.38.0.12:6379 172.38.0.13:6379 172.38.0.14:6379 172.38.0.15:6379 172.38.0.16:6379 --cluster-replicas 1</p><ul><li>redis-cli: Redis command-line client tool.</li><li>--cluster create: Command to create a Redis cluster.</li><li>172.38.0.11:6379 172.38.0.12:6379 172.38.0.13:6379 172.38.0.14:6379 172.38.0.15:6379 172.38.0.16:6379: Lists the various nodes in the cluster, including their IP addresses and port numbers. Here, 6 nodes are listed.</li><li>--cluster-replicas 1: Sets the number of replicas for each master node to 1, meaning each master node will have one corresponding replica node.</li></ul><p>You can provide more or fewer nodes as needed, and Redis will automatically configure the cluster accordingly. In this example, Redis inferred that you intended to create a cluster with 3 master nodes, each having a corresponding replica node.</p><p><strong>Redis Cluster Relationship Diagram:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6T2gBiISNDz3lB_HFiO3PQ.png" /></figure><p><strong>Usage:</strong></p><pre># Enter into redis client with cluster mode<br>$ redis-cli -c<br>127.0.0.1:6379&gt;<br><br># Check cluster<br>127.0.0.1:6379&gt; cluster nodes<br>11ef9dda18ee2fed754e5ce8baf0b04c2686ce56 172.38.0.12:6379@16379 master - 0 1705549415000 2 connected 5461-10922<br>b795fbd6344355a3a8d8bc9eae43b09553430874 172.38.0.16:6379@16379 slave 11ef9dda18ee2fed754e5ce8baf0b04c2686ce56 0 1705549416000 2 connected<br>b0954d066f6119abb5cc94307d7f66f6dabeaec4 172.38.0.15:6379@16379 slave 6d3685e325d476fadb9e0bd49a39b8406d9431a9 0 1705549416526 1 connected<br>6d3685e325d476fadb9e0bd49a39b8406d9431a9 172.38.0.11:6379@16379 myself,master - 0 1705549415000 1 connected 0-5460<br>900fb4a71efc86030b42230b10de2d25942c9e9a 172.38.0.14:6379@16379 slave e66e9af15132cd2b89f55b5fb890d2f18627aeed 0 1705549415000 3 connected<br>e66e9af15132cd2b89f55b5fb890d2f18627aeed 172.38.0.13:6379@16379 master - 0 1705549416426 3 connected 10923-16383<br><br># usage<br>127.0.0.1:6379&gt; set a b<br>-&gt; Redirected to slot [15495] located at 172.38.0.13:6379   # it is save in node 3 (master)<br>OK<br>172.38.0.13:6379&gt; get a<br>&quot;b&quot;<br><br>172.38.0.13:6379&gt; set key01 value01<br>OK<br>172.38.0.13:6379&gt; get key01<br>&quot;value01&quot;<br><br># We known the data is save in redis-3, we try to stop this container<br># In linux<br>root@jielim36:/home/jielim36# docker ps<br>CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                                                                                      NAMES<br>ccc478e3cb5f   redis     &quot;docker-entrypoint.s…&quot;   35 minutes ago   Up 35 minutes   0.0.0.0:6376-&gt;6379/tcp, :::6376-&gt;6379/tcp, 0.0.0.0:16376-&gt;16379/tcp, :::16376-&gt;16379/tcp   redis-6<br>c78636d05676   redis     &quot;docker-entrypoint.s…&quot;   36 minutes ago   Up 36 minutes   0.0.0.0:6375-&gt;6379/tcp, :::6375-&gt;6379/tcp, 0.0.0.0:16375-&gt;16379/tcp, :::16375-&gt;16379/tcp   redis-5<br>b701b548cdf8   redis     &quot;docker-entrypoint.s…&quot;   37 minutes ago   Up 37 minutes   0.0.0.0:6374-&gt;6379/tcp, :::6374-&gt;6379/tcp, 0.0.0.0:16374-&gt;16379/tcp, :::16374-&gt;16379/tcp   redis-4<br>7176ac3adb31   redis     &quot;docker-entrypoint.s…&quot;   37 minutes ago   Up 37 minutes   0.0.0.0:6373-&gt;6379/tcp, :::6373-&gt;6379/tcp, 0.0.0.0:16373-&gt;16379/tcp, :::16373-&gt;16379/tcp   redis-3<br>ac8020c72f3f   redis     &quot;docker-entrypoint.s…&quot;   37 minutes ago   Up 37 minutes   0.0.0.0:6372-&gt;6379/tcp, :::6372-&gt;6379/tcp, 0.0.0.0:16372-&gt;16379/tcp, :::16372-&gt;16379/tcp   redis-2<br>3918d85a6719   redis     &quot;docker-entrypoint.s…&quot;   40 minutes ago   Up 40 minutes   0.0.0.0:6371-&gt;6379/tcp, :::6371-&gt;6379/tcp, 0.0.0.0:16371-&gt;16379/tcp, :::16371-&gt;16379/tcp   redis-1<br><br># stop the redis-3<br>root@jielim36:/home/jielim36: docker stop redis-3<br>redis-3<br><br># And we go back to the redis, and trying to get the key &quot;a&quot; again<br>127.0.0.1:6379&gt; get a<br>-&gt; Redirected to slot [15495] located at 172.38.0.14:6379   # As you can see, you can get the data from the redis-4 now (slave node of the redis-3)<br>&quot;b&quot;  # retrieve data successful</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0313f063afb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Note]Docker Network]]></title>
            <link>https://medium.com/@jielim36/note-docker-network-7057df812743?source=rss-5c85604199dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7057df812743</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Lim Yee Jie]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 12:02:18 GMT</pubDate>
            <atom:updated>2024-01-22T02:07:57.917Z</atom:updated>
            <content:encoded><![CDATA[<p>Check your linux IP address: ip addr</p><pre>root@jielim36:/home# ip addr<br># lo (Loopback 环回)<br>1: lo: &lt;LOOPBACK,UP,LOWER_UP&gt; mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000<br>    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00<br>    inet 127.0.0.1/8 scope host lo<br>       valid_lft forever preferred_lft forever<br>    inet6 ::1/128 scope host<br>       valid_lft forever preferred_lft forever<br># eth0: physical network interface       <br>2: eth0: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1492 qdisc mq state UP group default qlen 1000<br>    link/ether 00:15:5d:20:dd:70 brd ff:ff:ff:ff:ff:ff<br>    inet 172.30.104.145/20 brd 172.30.111.255 scope global eth0<br>       valid_lft forever preferred_lft forever<br>    inet6 fe80::215:5dff:fe20:dd70/64 scope link<br>       valid_lft forever preferred_lft forever<br># Docker&#39;s default bridge network interface     <br>3: docker0: &lt;NO-CARRIER,BROADCAST,MULTICAST,UP&gt; mtu 1500 qdisc noqueue state DOWN group default<br>    link/ether 02:42:f5:91:7b:ce brd ff:ff:ff:ff:ff:ff<br>    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0<br>       valid_lft forever preferred_lft forever<br>    inet6 fe80::42:f5ff:fe91:7bce/64 scope link<br>       valid_lft forever preferred_lft forever</pre><ol><li>lo is the loopback interface used for local communication. It does not traverse the physical network and is a <strong>special interface for communication within the same machine</strong>.</li><li>eth0 is the physical network interface typically <strong>used for connecting to other devices in the network.</strong> The displayed IPv4 and MAC addresses are example values.</li><li>docker0 is Docker&#39;s default bridge network interface. It is used to connect Docker containers and <strong>provides network communication between the host and containers.</strong> This interface is typically virtual and created automatically when Docker starts.</li></ol><h3>Docker Network Case : Communicate between two container</h3><pre># prepare image and container<br>root@jielim36:/home# docker images<br>REPOSITORY   TAG       IMAGE ID       CREATED       SIZE<br>tomcat       latest    f1fd4dbf53f6   7 days ago    454MB<br>mysql        latest    73246731c4b0   4 weeks ago   619MB<br><br>root@jielim36:/home# docker run -d -P --name mytomcat tomcat<br>61c958d1e49caceda5cab5ebf615e109ade9bc778a46170428f5eb8f973321a4<br><br><br># Enter to the tomcat and check the ip address<br>$ docker exec -it mytomcat /bin/bash<br>$ apt update<br>$ apt install -y iproute2   # install the &quot;ip addr&quot; command<br>root@61c958d1e49c:/usr/local/tomcat# ip addr<br>1: lo: &lt;LOOPBACK,UP,LOWER_UP&gt; mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000<br>    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00<br>    inet 127.0.0.1/8 scope host lo<br>       valid_lft forever preferred_lft forever<br>22: eth0@if23: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc noqueue state UP group default<br>    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0<br>    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0<br>       valid_lft forever preferred_lft forever<br><br># you can also using &quot;docker inspect&quot; in linux to check this container&#39;s ip address<br>$ docker inspect mytomcat<br>[<br>    {<br>        ...,<br>        &quot;Networks&quot;: {<br>            &quot;bridge&quot;: {<br>                &quot;IPAMConfig&quot;: null,<br>                &quot;Links&quot;: null,<br>                &quot;Aliases&quot;: null,<br>                &quot;NetworkID&quot;: &quot;0afda71b3430a821cf7627d59bb02e4db72b8668ae79249c48cd93f90ecc024c&quot;,<br>                &quot;EndpointID&quot;: &quot;4274b7f11f1ed6a4025d1fd148d91d5bf0833ce445a77320be54d3bdf830c41b&quot;,<br>                &quot;Gateway&quot;: &quot;172.17.0.1&quot;,<br>                &quot;IPAddress&quot;: &quot;172.17.0.2&quot;,  # eth0<br>                &quot;IPPrefixLen&quot;: 16,<br>                &quot;IPv6Gateway&quot;: &quot;&quot;,<br>                &quot;GlobalIPv6Address&quot;: &quot;&quot;,<br>                &quot;GlobalIPv6PrefixLen&quot;: 0,<br>                &quot;MacAddress&quot;: &quot;02:42:ac:11:00:02&quot;,<br>                &quot;DriverOpts&quot;: null<br>            }<br>        },<br>        ...<br>    }<br>]<br><br><br># Now, you can try to ping your container in linux based on its eth0 ip address<br>root@jielim36:/home# ping 172.17.0.2<br>PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.<br>64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.381 ms<br>64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.051 ms<br>64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.049 ms<br>64 bytes from 172.17.0.2: icmp_seq=4 ttl=64 time=0.080 ms<br>64 bytes from 172.17.0.2: icmp_seq=5 ttl=64 time=0.047 ms<br>64 bytes from 172.17.0.2: icmp_seq=6 ttl=64 time=0.042 ms<br>64 bytes from 172.17.0.2: icmp_seq=7 ttl=64 time=0.055 ms<br>64 bytes from 172.17.0.2: icmp_seq=8 ttl=64 time=0.045 ms<br>64 bytes from 172.17.0.2: icmp_seq=9 ttl=64 time=0.047 ms<br>64 bytes from 172.17.0.2: icmp_seq=10 ttl=64 time=0.045 ms<br>64 bytes from 172.17.0.2: icmp_seq=11 ttl=64 time=0.051 ms<br>64 bytes from 172.17.0.2: icmp_seq=12 ttl=64 time=0.080 ms<br>64 bytes from 172.17.0.2: icmp_seq=13 ttl=64 time=0.042 ms<br>64 bytes from 172.17.0.2: icmp_seq=14 ttl=64 time=0.055 ms<br>64 bytes from 172.17.0.2: icmp_seq=15 ttl=64 time=0.047 ms<br>64 bytes from 172.17.0.2: icmp_seq=16 ttl=64 time=0.048 ms<br>^C  # Ctrl + C end the request<br>--- 172.17.0.2 ping statistics ---<br>16 packets transmitted, 16 received, 0% packet loss, time 15593ms<br>rtt min/avg/max/mdev = 0.042/0.072/0.381/0.080 ms<br>root@jielim36:/home#<br><br><br># We create other tomcat container and test to ping the first tomcat<br># in the new tomcat container, install iputils-ping package for &quot;ping&quot; command<br>$ apt-get update<br>$ apt-get install -y iputils-ping<br><br># Ping the first tomcat container (mytomcat) is working!<br>root@bab25a25b2e2:/usr/local/tomcat# ping 172.17.0.2<br>PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.<br>64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.369 ms<br>64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.057 ms<br>64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.084 ms<br>^C<br>--- 172.17.0.2 ping statistics ---<br>3 packets transmitted, 3 received, 0% packet loss, time 2079ms<br>rtt min/avg/max/mdev = 0.057/0.170/0.369/0.141 ms<br>root@bab25a25b2e2:/usr/local/tomcat#<br><br># We try to stop the first tomcat container (mytomcat) and ping again<br>root@jielim36:/home# docker stop mytomcat<br>mytomcat<br><br>root@jielim36:/home# docker exec -it tomcat02 /bin/bash<br>root@bab25a25b2e2:/usr/local/tomcat# ping 172.17.0.2<br>PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.<br>From 172.17.0.3 icmp_seq=1 Destination Host Unreachable # it&#39;s not working<br>From 172.17.0.3 icmp_seq=2 Destination Host Unreachable<br>From 172.17.0.3 icmp_seq=3 Destination Host Unreachable<br>From 172.17.0.3 icmp_seq=4 Destination Host Unreachable<br>From 172.17.0.3 icmp_seq=5 Destination Host Unreachable<br>^C<br>--- 172.17.0.2 ping statistics ---<br>6 packets transmitted, 0 received, +5 errors, 100% packet loss, time 5183ms<br>pipe 3</pre><h3>How the container communicate?</h3><pre>root@jielim36:/home/jielim36# ip addr<br>1: lo: &lt;LOOPBACK,UP,LOWER_UP&gt; mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000<br>    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00<br>    inet 127.0.0.1/8 scope host lo<br>       valid_lft forever preferred_lft forever<br>    inet6 ::1/128 scope host<br>       valid_lft forever preferred_lft forever<br>2: eth0: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1492 qdisc mq state UP group default qlen 1000<br>    link/ether 00:15:5d:20:dd:70 brd ff:ff:ff:ff:ff:ff<br>    inet 172.30.104.145/20 brd 172.30.111.255 scope global eth0<br>       valid_lft forever preferred_lft forever<br>    inet6 fe80::215:5dff:fe20:dd70/64 scope link<br>       valid_lft forever preferred_lft forever<br>3: docker0: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc noqueue state UP group default<br>    link/ether 02:42:f5:91:7b:ce brd ff:ff:ff:ff:ff:ff<br>    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0<br>       valid_lft forever preferred_lft forever<br>    inet6 fe80::42:f5ff:fe91:7bce/64 scope link<br>       valid_lft forever preferred_lft forever<br># No: 31       <br>31: vethaee4964@if30: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc noqueue master docker0 state UP group default<br>    link/ether 1e:b2:d1:c6:f7:d0 brd ff:ff:ff:ff:ff:ff link-netnsid 1<br>    inet6 fe80::1cb2:d1ff:fec6:f7d0/64 scope link<br>       valid_lft forever preferred_lft forever<br># No: 33<br>33: vethb23aebb@if32: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc noqueue master docker0 state UP group default<br>    link/ether 26:bb:52:c2:86:a5 brd ff:ff:ff:ff:ff:ff link-netnsid 2<br>    inet6 fe80::24bb:52ff:fec2:86a5/64 scope link<br>       valid_lft forever preferred_lft forever</pre><p>When you create a container, Docker and the container itself create a veth, and we call the veth of both sides veth-pair, which helps facilitate communication between the container and the docker0 bridge. For example, if we have currently created two Tomcat containers, our Docker instance will have two veth pairs, each corresponding to one of the Tomcat containers.</p><p><strong>Get the veth of the container</strong></p><pre># First tomcat container<br>root@jielim36:/home/jielim36# docker exec -it mytomcat /bin/bash<br>root@61c958d1e49c:/usr/local/tomcat# ip addr<br>1: lo: &lt;LOOPBACK,UP,LOWER_UP&gt; mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000<br>    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00<br>    inet 127.0.0.1/8 scope host lo<br>       valid_lft forever preferred_lft forever<br># No: 32       <br>32: eth0@if33: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc noqueue state UP group default<br>    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0<br>    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0<br>       valid_lft forever preferred_lft forever<br><br><br># Second tomcat container<br>root@bab25a25b2e2:/usr/local/tomcat# ip addr<br>1: lo: &lt;LOOPBACK,UP,LOWER_UP&gt; mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000<br>    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00<br>    inet 127.0.0.1/8 scope host lo<br>       valid_lft forever preferred_lft forever<br># No: 30       <br>30: eth0@if31: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc noqueue state UP group default<br>    link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff link-netnsid 0<br>    inet 172.17.0.3/16 brd 172.17.255.255 scope global eth0<br>       valid_lft forever preferred_lft forever</pre><p>In summary:</p><ol><li>Container 01:</li></ol><ul><li>Container: eth0@if33</li><li>docker0: vethb23aebb@if32</li></ul><p>2. Container 02:</p><ul><li>Container: eth0@if31</li><li>docker0: vethaee4964@if30</li></ul><p>3. docker0: 172.17.0.1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*GNjiKsNIk4PmhXBUUIJ6aA.png" /></figure><h3>Common Network Driver Type</h3><p>Check your docker network: docker network ls</p><pre>root@jielim36:/home/jielim36# docker network ls<br>NETWORK ID     NAME      DRIVER    SCOPE<br>0afda71b3430   bridge    bridge    local<br>7b841c303623   host      host      local<br>ed48a85b032b   none      null      local</pre><p><strong>1. Bridge:</strong></p><ul><li>Features: Default network driver that create an internal bridge network.</li><li>Purpose: Used for communication between containers running on the same host.</li><li>Example: docker run --network bridge</li></ul><p><strong>2. Host:</strong></p><ul><li>Features: Allows container to share the host’s network namespace, directly sharing the network stack with the host.</li><li>Purpose: Suitable for scenarios requiring maximum performance and minimal network isolation. Containers share IP addresses and port space with the host.</li><li>Example: docker run --network host</li></ul><p><strong>3. None:</strong></p><ul><li>Features: Containers have no network interfaces, meaning no network connection is assigned.</li><li>Purpose: Used in scenarios where no network connectivity is needed. Networking can be manually configured, or communication between containers can be achieved through other means.</li><li>Example: docker run --network none</li></ul><h3>Docker Network Command</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*MTkCX3mb2SUjgbsM1Er7Aw.png" /></figure><h3>Custom Network</h3><p>Command: docker network create</p><pre># optional<br>Options:<br>      --attachable           Enable manual container attachment<br>      --aux-address map      Auxiliary IPv4 or IPv6 addresses used by Network driver (default map[])<br>      --config-from string   The network from which to copy the configuration<br>      --config-only          Create a configuration only network<br>  -d, --driver string        Driver to manage the Network (default &quot;bridge&quot;)<br>      --gateway strings      IPv4 or IPv6 Gateway for the master subnet<br>      --ingress              Create swarm routing-mesh network<br>      --internal             Restrict external access to the network<br>      --ip-range strings     Allocate container ip from a sub-range<br>      --ipam-driver string   IP Address Management Driver (default &quot;default&quot;)<br>      --ipam-opt map         Set IPAM driver specific options (default map[])<br>      --ipv6                 Enable IPv6 networking<br>      --label list           Set metadata on a network<br>  -o, --opt map              Set driver specific options (default map[])<br>      --scope string         Control the network&#39;s scope<br>      --subnet strings       Subnet in CIDR format that represents a network segment<br><br># Customize a network<br># --driver bridge : specific you driver type<br># --subnet : 192.168.0.0/16<br># --gateway : 192.168.0.1<br>$ docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynetwork<br>3284f59b2ec4aeee95ded4093297b699fbd6b641146ea8e706aedf96d0b56110    # Success <br><br># check your network<br>$ docker network ls<br>NETWORK ID     NAME        DRIVER    SCOPE<br>0afda71b3430   bridge      bridge    local<br>7b841c303623   host        host      local<br>3284f59b2ec4   mynetwork   bridge    local  # Exists<br>ed48a85b032b   none        null      local<br><br># check details<br># docker network inspect &lt;custom_network_name&gt;<br>$ docker network inspect mynetwork<br>[<br>    {<br>        &quot;Name&quot;: &quot;mynetwork&quot;,<br>        &quot;Id&quot;: &quot;3284f59b2ec4aeee95ded4093297b699fbd6b641146ea8e706aedf96d0b56110&quot;,<br>        &quot;Created&quot;: &quot;2024-01-17T16:08:38.419681093+08:00&quot;,<br>        &quot;Scope&quot;: &quot;local&quot;,<br>        &quot;Driver&quot;: &quot;bridge&quot;,<br>        &quot;EnableIPv6&quot;: false,<br>        &quot;IPAM&quot;: {<br>            &quot;Driver&quot;: &quot;default&quot;,<br>            &quot;Options&quot;: {},<br>            &quot;Config&quot;: [<br>                {<br>                    &quot;Subnet&quot;: &quot;192.168.0.0/16&quot;,<br>                    &quot;Gateway&quot;: &quot;192.168.0.1&quot;<br>                }<br>            ]<br>        },<br>        &quot;Internal&quot;: false,<br>        &quot;Attachable&quot;: false,<br>        &quot;Ingress&quot;: false,<br>        &quot;ConfigFrom&quot;: {<br>            &quot;Network&quot;: &quot;&quot;<br>        },<br>        &quot;ConfigOnly&quot;: false,<br>        &quot;Containers&quot;: {},<br>        &quot;Options&quot;: {},<br>        &quot;Labels&quot;: {}<br>    }<br>]</pre><p><strong>Create a container with the custom network</strong><br>Command: docker run --net &lt;your_custom_network_name&gt; &lt;other_optional&gt; &lt;image&gt;</p><pre># create two container called &quot;tomcat03&quot; and &quot;tomcat04&quot; based on the same custom network<br>$ docker run -d -P --name tomcat03 --net mynetwork tomcat<br>fcd8005dbff5c6304503bb81d75fc1bf47e58af34b499432e6b67795c7aaf6b0<br><br>$ docker run -d -P --name tomcat04 --net mynetwork tomcat<br>1fa025a13661e441f252013f9b0f1cb891e27f27519711089e44f4f07cdec14b<br><br><br># check the custom network now<br>$ docker network inspect mynetwork<br>[<br>    {<br>        &quot;Name&quot;: &quot;mynetwork&quot;,<br>        &quot;Id&quot;: &quot;3284f59b2ec4aeee95ded4093297b699fbd6b641146ea8e706aedf96d0b56110&quot;,<br>        &quot;Created&quot;: &quot;2024-01-17T16:08:38.419681093+08:00&quot;,<br>        &quot;Scope&quot;: &quot;local&quot;,<br>        &quot;Driver&quot;: &quot;bridge&quot;,<br>        &quot;EnableIPv6&quot;: false,<br>        &quot;IPAM&quot;: {<br>            &quot;Driver&quot;: &quot;default&quot;,<br>            &quot;Options&quot;: {},<br>            &quot;Config&quot;: [<br>                {<br>                    &quot;Subnet&quot;: &quot;192.168.0.0/16&quot;,<br>                    &quot;Gateway&quot;: &quot;192.168.0.1&quot;<br>                }<br>            ]<br>        },<br>        &quot;Internal&quot;: false,<br>        &quot;Attachable&quot;: false,<br>        &quot;Ingress&quot;: false,<br>        &quot;ConfigFrom&quot;: {<br>            &quot;Network&quot;: &quot;&quot;<br>        },<br>        &quot;ConfigOnly&quot;: false,<br>        &quot;Containers&quot;: { # Container information<br>            &quot;1fa025a13661e441f252013f9b0f1cb891e27f27519711089e44f4f07cdec14b&quot;: {<br>                &quot;Name&quot;: &quot;tomcat04&quot;,<br>                &quot;EndpointID&quot;: &quot;dcdc2ccb6c41abe1b5edf48b6c068e944a514da22ee40a881bb2929b91ad2a76&quot;,<br>                &quot;MacAddress&quot;: &quot;02:42:c0:a8:00:03&quot;,<br>                &quot;IPv4Address&quot;: &quot;192.168.0.3/16&quot;, # the ip address is based on the subnet of the custom network<br>                &quot;IPv6Address&quot;: &quot;&quot;<br>            },<br>            &quot;fcd8005dbff5c6304503bb81d75fc1bf47e58af34b499432e6b67795c7aaf6b0&quot;: {<br>                &quot;Name&quot;: &quot;tomcat03&quot;,<br>                &quot;EndpointID&quot;: &quot;37e93aa0229ac4ef2295a47e216cd08ee90260905cbab20ee76c9c45499610ef&quot;,<br>                &quot;MacAddress&quot;: &quot;02:42:c0:a8:00:02&quot;,<br>                &quot;IPv4Address&quot;: &quot;192.168.0.2/16&quot;,<br>                &quot;IPv6Address&quot;: &quot;&quot;<br>            }<br>        },<br>        &quot;Options&quot;: {},<br>        &quot;Labels&quot;: {}<br>    }<br>]</pre><p>As you can see, after you create the container based on the custom network. The custom network will save the information about the containers.</p><p>Multiple containers (tomcat03 and tomcat04) using the same custom network can communicate with each other more conveniently.</p><p><strong>Advantages:</strong></p><p>1. You can ping other container through their container name</p><pre># In tomcat03 container<br>root@fcd8005dbff5:/usr/local/tomcat: ping tomcat04 # ping other container based on the target name<br>PING tomcat04 (192.168.0.3) 56(84) bytes of data.<br>64 bytes from tomcat04.mynetwork (192.168.0.3): icmp_seq=1 ttl=64 time=0.251 ms<br>64 bytes from tomcat04.mynetwork (192.168.0.3): icmp_seq=2 ttl=64 time=0.059 ms<br>64 bytes from tomcat04.mynetwork (192.168.0.3): icmp_seq=3 ttl=64 time=0.088 ms<br>64 bytes from tomcat04.mynetwork (192.168.0.3): icmp_seq=4 ttl=64 time=0.206 ms<br>^C<br>--- tomcat04 ping statistics ---<br>4 packets transmitted, 4 received, 0% packet loss, time 3090ms<br>rtt min/avg/max/mdev = 0.059/0.151/0.251/0.079 ms</pre><p><strong>2. Isolating Network Traffic:</strong> Custom networks provide better network isolation, allowing containers to run more seamlessly on the same host without concerns about port conflicts. Each custom network has its own IP address range, preventing both port and IP address conflicts.</p><p><strong>3. Custom Subnets:</strong> You can define subnets for custom networks to have finer control over the allocation of container IP addresses. This is useful for avoiding conflicts with other networks, implementing more complex network topologies, or meeting specific requirements.</p><p><strong>4. Connecting Multiple Containers: </strong>Custom networks allow the connection of multiple containers, creating a logically segmented network to meet the needs of applications. You can easily connect multiple containers to the same network, facilitating communication between them while maintaining isolation from other networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*las_sWbRPVr2cjp0ef-l6g.png" /></figure><h3>Network connect: Communicate between two network</h3><p>How do we communicate between Container B and Container D</p><pre># Get the IP address of the container B.<br>root@jielim36:/home/jielim36# docker exec -it tomcat02 ip addr<br>1: lo: &lt;LOOPBACK,UP,LOWER_UP&gt; mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000<br>    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00<br>    inet 127.0.0.1/8 scope host lo<br>       valid_lft forever preferred_lft forever<br>7: eth0@if8: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc noqueue state UP group default<br>    link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff link-netnsid 0<br>    inet 172.17.0.3/16 brd 172.17.255.255 scope global eth0<br>       valid_lft forever preferred_lft forever<br><br># Get the IP address of the container D.       <br>root@jielim36:/home/jielim36# docker exec -it tomcat04 ip addr<br>1: lo: &lt;LOOPBACK,UP,LOWER_UP&gt; mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000<br>    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00<br>    inet 127.0.0.1/8 scope host lo<br>       valid_lft forever preferred_lft forever<br>11: eth0@if12: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc noqueue state UP group default<br>    link/ether 02:42:c0:a8:00:03 brd ff:ff:ff:ff:ff:ff link-netnsid 0<br>    inet 192.168.0.3/16 brd 192.168.255.255 scope global eth0<br>       valid_lft forever preferred_lft forever<br><br># Ping through container name (container B ping D)<br>root@jielim36:/home/jielim36# docker exec -it tomcat02 ping tomcat04<br>ping: tomcat04: Name or service not known   # it&#39;s not wprking<br><br># Ping through IP address (container B ping D)<br>root@jielim36:/home/jielim36# docker exec -it tomcat02 ping 192.168.0.3<br>PING 192.168.0.3 (192.168.0.3) 56(84) bytes of data.<br>^C<br>--- 192.168.0.3 ping statistics ---<br>13 packets transmitted, 0 received, 100% packet loss, time 12516ms  # it&#39;s working but network is very slow</pre><p>For this situation, we can try to connect the docker0&#39;s container (container B) and mynetwork (custom network).</p><p>Command: docker network connect &lt;custom_network&gt; &lt;container_name&gt;</p><pre>Connect a container to a network<br><br>Options:<br>      --alias strings           Add network-scoped alias for the container<br>      --driver-opt strings      driver options for the network<br>      --ip string               IPv4 address (e.g., &quot;172.30.100.104&quot;)<br>      --ip6 string              IPv6 address (e.g., &quot;2001:db8::33&quot;)<br>      --link list               Add link to another container<br>      --link-local-ip strings   Add a link-local address for the container<br><br># Usage<br>$ docker network connect mynetwork tomcat02 # tomcat02 (container B) connect to the custom network<br><br># check the details of the custom network<br>root@jielim36:/home/jielim36# docker network inspect mynetwork<br>[<br>    {<br>        &quot;Name&quot;: &quot;mynetwork&quot;,<br>        &quot;Id&quot;: &quot;3284f59b2ec4aeee95ded4093297b699fbd6b641146ea8e706aedf96d0b56110&quot;,<br>        &quot;Created&quot;: &quot;2024-01-17T16:08:38.419681093+08:00&quot;,<br>        &quot;Scope&quot;: &quot;local&quot;,<br>        &quot;Driver&quot;: &quot;bridge&quot;,<br>        &quot;EnableIPv6&quot;: false,<br>        &quot;IPAM&quot;: {<br>            &quot;Driver&quot;: &quot;default&quot;,<br>            &quot;Options&quot;: {},<br>            &quot;Config&quot;: [<br>                {<br>                    &quot;Subnet&quot;: &quot;192.168.0.0/16&quot;,<br>                    &quot;Gateway&quot;: &quot;192.168.0.1&quot;<br>                }<br>            ]<br>        },<br>        &quot;Internal&quot;: false,<br>        &quot;Attachable&quot;: false,<br>        &quot;Ingress&quot;: false,<br>        &quot;ConfigFrom&quot;: {<br>            &quot;Network&quot;: &quot;&quot;<br>        },<br>        &quot;ConfigOnly&quot;: false,<br>        &quot;Containers&quot;: {<br>            &quot;1fa025a13661e441f252013f9b0f1cb891e27f27519711089e44f4f07cdec14b&quot;: {<br>                &quot;Name&quot;: &quot;tomcat04&quot;,<br>                &quot;EndpointID&quot;: &quot;35cbc41eea487faba79b181239747da194dd3e6d9c9d514d663da474c19771b4&quot;,<br>                &quot;MacAddress&quot;: &quot;02:42:c0:a8:00:03&quot;,<br>                &quot;IPv4Address&quot;: &quot;192.168.0.3/16&quot;,<br>                &quot;IPv6Address&quot;: &quot;&quot;<br>            },<br>            &quot;bab25a25b2e2f71f4c423b0a1f39cb08729544cae5986748594841750832a305&quot;: {<br>                &quot;Name&quot;: &quot;tomcat02&quot;, # Connected<br>                &quot;EndpointID&quot;: &quot;d679d646699d79d73707a34b19f650710d003e5c612993088d7602f373ae0b15&quot;,<br>                &quot;MacAddress&quot;: &quot;02:42:c0:a8:00:04&quot;,<br>                &quot;IPv4Address&quot;: &quot;192.168.0.4/16&quot;,<br>                &quot;IPv6Address&quot;: &quot;&quot;<br>            },<br>            &quot;fcd8005dbff5c6304503bb81d75fc1bf47e58af34b499432e6b67795c7aaf6b0&quot;: {<br>                &quot;Name&quot;: &quot;tomcat03&quot;,<br>                &quot;EndpointID&quot;: &quot;a9570bfb81b0606e7ca9bdefbcf646a3caf8140bff5a8bdc3576f15f16935bfe&quot;,<br>                &quot;MacAddress&quot;: &quot;02:42:c0:a8:00:02&quot;,<br>                &quot;IPv4Address&quot;: &quot;192.168.0.2/16&quot;,<br>                &quot;IPv6Address&quot;: &quot;&quot;<br>            }<br>        },<br>        &quot;Options&quot;: {},<br>        &quot;Labels&quot;: {}<br>    }<br>]<br><br><br># Ping again<br># ping through container name (it&#39;s working)<br>root@jielim36:/home/jielim36# docker exec tomcat02 ping tomcat04<br>PING tomcat04 (192.168.0.3) 56(84) bytes of data.<br>64 bytes from tomcat04.mynetwork (192.168.0.3): icmp_seq=1 ttl=64 time=0.059 ms<br>64 bytes from tomcat04.mynetwork (192.168.0.3): icmp_seq=2 ttl=64 time=0.068 ms<br>64 bytes from tomcat04.mynetwork (192.168.0.3): icmp_seq=3 ttl=64 time=0.075 ms<br>64 bytes from tomcat04.mynetwork (192.168.0.3): icmp_seq=4 ttl=64 time=0.077 ms<br>^C<br><br># ping through IP address (it&#39;s working and faster)<br>root@jielim36:/home/jielim36# docker exec tomcat02 ping 192.168.0.3<br>PING 192.168.0.3 (192.168.0.3) 56(84) bytes of data.<br>64 bytes from 192.168.0.3: icmp_seq=1 ttl=64 time=0.056 ms<br>64 bytes from 192.168.0.3: icmp_seq=2 ttl=64 time=0.060 ms<br>64 bytes from 192.168.0.3: icmp_seq=3 ttl=64 time=0.066 ms<br>64 bytes from 192.168.0.3: icmp_seq=4 ttl=64 time=0.095 ms<br>64 bytes from 192.168.0.3: icmp_seq=5 ttl=64 time=0.053 ms</pre><p>Now, the Container B (tomcat02) is connected with Custom Network (mynetwork) now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vi0I8B4mpfOpSulqH7HBg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7057df812743" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Note] Docker Basic Command]]></title>
            <link>https://medium.com/@jielim36/note-docker-basic-command-934cc6a2a49d?source=rss-5c85604199dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/934cc6a2a49d</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Lim Yee Jie]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 13:00:59 GMT</pubDate>
            <atom:updated>2024-01-19T13:11:53.254Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker Command:</h3><blockquote><em>Please use root permission</em></blockquote><p>Official Document Command: <a href="https://docs.docker.com/engine/reference/commandline/cli/">https://docs.docker.com/engine/reference/commandline/cli/</a></p><h3>Basic information</h3><pre>docker version          # show docker version information (client and server)<br>docker info             # show docker system information: images, containers,OS...<br>docker &lt;command&gt; --help # show command details, For example: docker pull --help</pre><h3>Image Command</h3><p><a href="https://docs.docker.com/engine/reference/commandline/images/">https://docs.docker.com/engine/reference/commandline/images/</a></p><p>docker images : show all images</p><pre>REPOSITORY    TAG       IMAGE ID       CREATED        SIZE<br>hello-world   latest    d2c94e258dcb   8 months ago   13.3kB# optional<br>-a , -all : list all images<br>-q, -quiet : only return the image id<br>-aq : show all images and only return image id<br>&lt;repository&gt; : show all images by repositoy, For example:<br><br>$ docker images java<br>REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE<br>java                8                   308e519aac60        6 days ago          824.5 MB<br>java                7                   493d82594c15        3 months ago        656.3 MB<br>java                latest              2711b1d6f3aa        5 months ago        603.9 MB</pre><p>Difference between docker images and docker images -a:<br><strong>docker images</strong> shows only the top non-dangling images, while <strong>docker images -a</strong> displays all images, including intermediate layers and dangling images. Choose the appropriate command based on your need to view Docker images.</p><p>docker search &lt;imageName&gt; : Search Image</p><pre>bash<br>$ docker search mysqlNAME                            DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED<br>mysql                           MySQL is a widely used, open-source relation…   14759     [OK]<br>mariadb                         MariaDB Server is a high performing open sou…   5632      [OK]<br>percona                         Percona Server is a fork of the MySQL relati…   623       [OK]<br>phpmyadmin                      phpMyAdmin - A web interface for MySQL and M…   927       [OK]<br>bitnami/mysql                   Bitnami MySQL Docker Image                      104                  [OK]<br>...<br><br># Optional<br>--filter<br>Example:<br>$ docker search mysql --filter=stars=3000  # search the image with more than 3000 stars.<br>NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED<br>mysql     MySQL is a widely used, open-source relation…   14759     [OK]<br>mariadb   MariaDB Server is a high performing open sou…   5632      [OK]</pre><p>docker pull &lt;image&gt;: Download Image</p><pre>$ docker pull mysql         # Download MySQL with latest version<br><br>Result:<br>root@jielim36:/home/jielim36# docker pull mysql<br>Using default tag: latest       # if didn&#39;t write tag, default is download latest version<br><br>latest: Pulling from library/mysql<br>bce031bc522d: Pull complete     # Download the image that mysql needed, if there is already download, will return `Already exists`<br>cf7e9f463619: Pull complete<br>105f403783c7: Pull complete<br>878e53a613d8: Pull complete<br>2a362044e79f: Pull complete<br>6e4df4f73cfe: Pull complete<br>69263d634755: Pull complete<br>fe5e85549202: Pull complete<br>5c02229ce6f1: Pull complete<br>7320aa32bf42: Pull complete<br>Digest: sha256:4ef30b2c11a3366d7bb9ad95c70c0782ae435df52d046553ed931621ea36ffa5     #signature<br>Status: Downloaded newer image for mysql:latest<br>docker.io/library/mysql:latest      # real path in docker<br><br># This two command is same:<br>1. docker pull mysql<br>2. docker pull docker.io/library/mysql:latest<br><br>--------------------------------------------------------------------------<br><br><br># Download with specific version (you need to go official page to see there are what version):<br>$ docker pull mysql:5.7 # download version 5.7<br><br>Result:<br>root@jielim36:/home/jielim36# docker pull mysql:5.7<br>5.7: Pulling from library/mysql<br>20e4dcae4c69: Pull complete<br>1c56c3d4ce74: Pull complete<br>e9f03a1c24ce: Pull complete<br>68c3898c2015: Pull complete<br>6b95a940e7b6: Pull complete<br>90986bb8de6e: Pull complete<br>ae71319cb779: Pull complete<br>ffc89e9dfd88: Pull complete<br>43d05e938198: Pull complete<br>064b2d298fba: Pull complete<br>df9a4d85569b: Pull complete<br>Digest: sha256:4bc6bc963e6d8443453676cae56536f4b8156d78bae03c0145cbe47c2aad73bb<br>Status: Downloaded newer image for mysql:5.7<br>docker.io/library/mysql:5.7<br><br>--------------------------------------------------------------------------<br><br>Check Docker Images:<br>root@jielim36:/home/jielim36# docker images<br><br>REPOSITORY    TAG       IMAGE ID       CREATED        SIZE<br>mysql         latest    73246731c4b0   3 weeks ago    619MB<br>mysql         5.7       5107333e08a8   4 weeks ago    501MB<br>hello-world   latest    d2c94e258dcb   8 months ago   13.3kB<br><br>```</pre><p>docker rmi &lt;image id&gt; : Delete image by image id</p><pre>bash<br>$ docker rmi 5107333e08a8       # Delete mysql:5.7<br><br>Result:<br>root@jielim36:/home/jielim36# docker rmi 5107333e08a8<br>Untagged: mysql:5.7<br>Untagged: mysql@sha256:4bc6bc963e6d8443453676cae56536f4b8156d78bae03c0145cbe47c2aad73bb<br>Deleted: sha256:5107333e08a87b836d48ff7528b1e84b9c86781cc9f1748bbc1b8c42a870d933<br>Deleted: sha256:37fd5f1492d4e9cb540c52c26655f220568050438f804275e886200c8807ffb4<br>Deleted: sha256:1105a50d3483cb9f970e70cf5163e3352f0b2fe2ff07c6abcca6f34228e76dc5<br>Deleted: sha256:94187496c18bb11b78e71017f2774ad3c0a734da9749a46e917c4239504e9322<br>Deleted: sha256:ae59716eae3be604a4fd43e86fd2ad504cb06c89cc064c73c78eee651e675805<br>Deleted: sha256:97d26ca29ec287ff4bd09a49602c44cbcabcf3303ddc726b3b94cbe26dfe1c94<br>Deleted: sha256:27303974d12144264b32b8936ca7c90d72bdba939a9e791010201b3b1717c4c4<br>Deleted: sha256:4d4483f06dbe01282c10cb9e429a0be826c18c61048f7860dad49ae7f6bac927<br>Deleted: sha256:3b73a6f6b3298c568dcfb8fa5e96c581a1b5c0ad395b0c38f9addd0c79703124<br>Deleted: sha256:46446bf265a411a4a13a4adc86f60c9e0479a2e03273c98cafab7bc4151dd2bc<br>Deleted: sha256:1d5264146b09a27a8fc6801dc239a4962582ed27dd2fbd8ee708463a1857b06b<br>Deleted: sha256:cff044e186247f93aa52554c96d77143cc92f99b2b55914038d0941fddeb6623<br><br>root@jielim36:/home/jielim36# docker images<br>REPOSITORY    TAG       IMAGE ID       CREATED        SIZE<br>mysql         latest    73246731c4b0   3 weeks ago    619MB<br>hello-world   latest    d2c94e258dcb   8 months ago   13.3kB<br><br># Optional:<br>--force , -f : Force removal of the image<br>--no-prune : Do not delete untagged parents<br><br># How to delete all images<br>$ docker rmi -f $(docker images -aq)    # Similar with SQL: query all images and return image ID only. Then, delete image according by the query id<br><br>root@jielim36:/home/jielim36# docker images<br>REPOSITORY   TAG       IMAGE ID   CREATED   SIZE<br>...nothing</pre><h3>Container Command:</h3><blockquote><em>We download the debian for testing<br>command: </em><strong>docker pull debian</strong></blockquote><p>docker run &lt;optional&gt; &lt;imageName&gt;: Create and Run the image in a Container</p><pre>docker run [optional] &lt;imageName&gt;<br># optional<br>--name=&quot;MySQL_01&quot;       # Run a container and called it MySQL_01, if you have run two mysql container, you can use it to make diffrent.<br>-d      # Running in background<br>-it     # Run and enter to the container<br>-p      # specific the port number of this container, <br>    For example: <br>    -p 8080:8080 (HostPortNumber:ContainerPortNumber)<br>    -p 8080 (Container Port Number)<br>    -p ip:HostPortNumber:ContainerPortNumber<br>-P      # Random port number</pre><p>exit: Exit container and stop running (Please make sure you are inside the container)</p><p>Ctrl + P + Q: Exit container but keep running</p><p>docker ps: show the running containers (ps: Process Status)</p><pre># Optional<br>-a : Show the container include running before<br>    Example:<br>        root@jielim36:/home/jielim36# docker ps -a<br>        CONTAINER ID   IMAGE          COMMAND    CREATED         STATUS                     PORTS     NAMES<br>        b39b85a03158   debian         &quot;bash&quot;     4 minutes ago   Exited (0) 3 minutes ago             awesome_snyder<br>        206f0167580b   d2c94e258dcb   &quot;/hello&quot;   4 hours ago     Exited (0) 4 hours ago               naughty_driscoll<br>        27fbd9a1a60b   d2c94e258dcb   &quot;/hello&quot;   4 hours ago     Exited (0) 4 hours ago               keen_morse<br>        575bcc088c72   d2c94e258dcb   &quot;/hello&quot;   4 hours ago     Exited (0) 4 hours ago               happy_payne<br>        cc8c5afe5942   d2c94e258dcb   &quot;/hello&quot;   4 hours ago     Exited (0) 4 hours ago               keen_solomon<br><br>-n=? : Only show ? rows data<br>    Example:<br>        root@jielim36:/home/jielim36# docker ps -n3 # only return 3 data<br>        CONTAINER ID   IMAGE          COMMAND    CREATED         STATUS                     PORTS     NAMES<br>        b39b85a03158   debian         &quot;bash&quot;     8 minutes ago   Exited (0) 7 minutes ago             awesome_snyder<br>        206f0167580b   d2c94e258dcb   &quot;/hello&quot;   4 hours ago     Exited (0) 4 hours ago               naughty_driscoll<br>        27fbd9a1a60b   d2c94e258dcb   &quot;/hello&quot;   4 hours ago     Exited (0) 4 hours ago               keen_morse<br>-q : Only return container id<br>    For example:<br>        root@jielim36:/home/jielim36# docker ps -n3 -q # only return 3 data with the container id<br>        b39b85a03158<br>        206f0167580b<br>        27fbd9a1a60b</pre><p>docker rm &lt;containerID&gt; : Delete Container</p><pre># Optional<br>-f : Force the removal of a running container (uses SIGKILL) <br><br>root@jielim36:/home/jielim36# docker ps -a<br>CONTAINER ID   IMAGE          COMMAND    CREATED          STATUS                      PORTS     NAMES<br>66f409f16cc9   debian         &quot;bash&quot;     6 minutes ago    Up 6 minutes                          naughty_black<br>b39b85a03158   debian         &quot;bash&quot;     20 minutes ago   Exited (0) 19 minutes ago             awesome_snyder<br>206f0167580b   d2c94e258dcb   &quot;/hello&quot;   4 hours ago      Exited (0) 4 hours ago                naughty_driscoll<br>27fbd9a1a60b   d2c94e258dcb   &quot;/hello&quot;   4 hours ago      Exited (0) 4 hours ago                keen_morse<br>575bcc088c72   d2c94e258dcb   &quot;/hello&quot;   4 hours ago      Exited (0) 4 hours ago                happy_payne<br>cc8c5afe5942   d2c94e258dcb   &quot;/hello&quot;   4 hours ago      Exited (0) 4 hours ago                keen_solomon<br><br>root@jielim36:/home/jielim36# docker rm b39b85a03158<br>b39b85a03158<br><br># Result<br>root@jielim36:/home/jielim36# docker ps -a<br>CONTAINER ID   IMAGE          COMMAND    CREATED         STATUS                   PORTS     NAMES<br>66f409f16cc9   debian         &quot;bash&quot;     7 minutes ago   Up 7 minutes                       naughty_black<br>206f0167580b   d2c94e258dcb   &quot;/hello&quot;   4 hours ago     Exited (0) 4 hours ago             naughty_driscoll<br>27fbd9a1a60b   d2c94e258dcb   &quot;/hello&quot;   4 hours ago     Exited (0) 4 hours ago             keen_morse<br>575bcc088c72   d2c94e258dcb   &quot;/hello&quot;   4 hours ago     Exited (0) 4 hours ago             happy_payne<br>cc8c5afe5942   d2c94e258dcb   &quot;/hello&quot;   4 hours ago     Exited (0) 4 hours ago             keen_solomon<br><br>------------------------------------------------------------------------<br><br># Delete the running container<br>root@jielim36:/home/jielim36# docker ps -a<br>CONTAINER ID   IMAGE          COMMAND    CREATED         STATUS                   PORTS     NAMES<br>66f409f16cc9   debian         &quot;bash&quot;     9 minutes ago   Up 9 minutes                       naughty_black<br>206f0167580b   d2c94e258dcb   &quot;/hello&quot;   4 hours ago     Exited (0) 4 hours ago             naughty_driscoll<br>27fbd9a1a60b   d2c94e258dcb   &quot;/hello&quot;   4 hours ago     Exited (0) 4 hours ago             keen_morse<br>575bcc088c72   d2c94e258dcb   &quot;/hello&quot;   4 hours ago     Exited (0) 4 hours ago             happy_payne<br>cc8c5afe5942   d2c94e258dcb   &quot;/hello&quot;   4 hours ago     Exited (0) 4 hours ago             keen_solomon<br>root@jielim36:/home/jielim36# docker rm 66f409f16cc9<br>Error response from daemon: You cannot remove a running container 66f409f16cc9422a3f12b46b097602afce0ba613b07c0931bbc9825c2909fb27. Stop the container before attempting removal or force remove<br><br># Use -f optional to delete with force<br>root@jielim36:/home/jielim36# docker rm -f 66f409f16cc9<br>66f409f16cc9<br><br># Deleted all container<br>$ docker rm -f $(docker ps -aq)</pre><p>Start and End Container:</p><pre>docker start &lt;containerID&gt;      # Start a container<br>docker restart &lt;containerID&gt;    # Restart a container<br>docker stop &lt;containerID&gt;       # Stop the running container<br>docker kill &lt;containerID&gt;       # (Force) Stop the running container<br><br>Example:<br># Find the running container<br>root@jielim36:/home/jielim36# docker ps <br>CONTAINER ID   IMAGE     COMMAND   CREATED          STATUS          PORTS     NAMES<br>81b1ef821f70   debian    &quot;bash&quot;    17 seconds ago   Up 17 seconds             admiring_elion<br><br># Stop the running container<br>root@jielim36:/home/jielim36# docker stop 81b1ef821f70<br>81b1ef821f70<br><br># Check the running container, and there is nothing container is running...<br>root@jielim36:/home/jielim36# docker ps<br>CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES<br><br># Start the container stop just now<br>root@jielim36:/home/jielim36# docker start 81b1ef821f70<br>81b1ef821f0<br><br># Check again, and the specific container we start just now is running now...<br>root@jielim36:/home/jielim36# docker ps<br>CONTAINER ID   IMAGE     COMMAND   CREATED              STATUS         PORTS     NAMES<br>81b1ef821f70   debian    &quot;bash&quot;    About a minute ago   Up 3 seconds             admiring_elion</pre><p>docker exec: Enter the running container:</p><pre>$ docker exec -it &lt;containerID&gt; &lt;command in container&gt;<br><br># Example: go into Debian container<br>root@jielim36:/home/jielim36# docker exec -it 81b1ef821f70 /bin/bash<br>OR</pre><p>docker logs &lt;containerID&gt;: show the log of the container</p><pre># Return all log history (no keep tracking new logs)<br>root@jielim36:/home/jielim36# docker logs 81b1ef821f70<br>root@81b1ef821f70:/# ls<br>bin   dev  home  lib32  libx32  mnt  proc  run   srv  tmp  var<br>boot  etc  lib   lib64  media   opt  root  sbin  sys  usr<br><br># optional<br>-f : Follow log output<br>-t : show timestamps, and keep tracking the logs (持续输出新的日志)<br>You can combine to -tf<br><br>--tail &lt;number&gt;: return X rows<br><br># return maximum 10 row logs, and keep tracking the new logs, it would not automatic ending.<br>$ docker log -t -f --tail 10 &lt;containerID&gt;</pre><p>docker top &lt;ContainerID&gt;: Check the process status about this container</p><pre>For example: check debian container<br>root@jielim36:/home/jielim36# docker top 81b1ef821f70<br>UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD<br>root                737                 717                 0                   19:42               pts/0               00:00:00            bash</pre><p>docker inspect &lt;ContainerID&gt;: Check the meta data of the container</p><pre># By default, docker inspect will render results in a JSON array<br>root@jielim36:/home/jielim36# docker inspect 81b1ef821f70<br>[<br>    {<br>        &quot;Id&quot;: &quot;81b1ef821f70efb26990934d3f2f242912df0df03d6bd6d77b33c5f64c93dbe1&quot;,<br>        &quot;Created&quot;: &quot;2024-01-12T07:24:07.393141112Z&quot;,<br>        &quot;Path&quot;: &quot;bash&quot;,<br>        &quot;Args&quot;: [],<br>        &quot;State&quot;: {<br>            &quot;Status&quot;: &quot;running&quot;,<br>            &quot;Running&quot;: true,<br>            &quot;Paused&quot;: false,<br>            &quot;Restarting&quot;: false,<br>            &quot;OOMKilled&quot;: false,<br>            &quot;Dead&quot;: false,<br>            &quot;Pid&quot;: 737,<br>            &quot;ExitCode&quot;: 0,<br>            &quot;Error&quot;: &quot;&quot;,<br>            &quot;StartedAt&quot;: &quot;2024-01-12T11:42:54.631373066Z&quot;,<br>            &quot;FinishedAt&quot;: &quot;2024-01-12T11:39:05.694749179Z&quot;<br>        },<br>        &quot;Image&quot;: &quot;sha256:a6916e41aa871b09260f8949fe3c34570719f1c92ffe87d515b7eb702ebaebb1&quot;,<br>        &quot;ResolvConfPath&quot;: &quot;/var/lib/docker/containers/81b1ef821f70efb26990934d3f2f242912df0df03d6bd6d77b33c5f64c93dbe1/resolv.conf&quot;,<br>        &quot;HostnamePath&quot;: &quot;/var/lib/docker/containers/81b1ef821f70efb26990934d3f2f242912df0df03d6bd6d77b33c5f64c93dbe1/hostname&quot;,<br>        &quot;HostsPath&quot;: &quot;/var/lib/docker/containers/81b1ef821f70efb26990934d3f2f242912df0df03d6bd6d77b33c5f64c93dbe1/hosts&quot;,<br>        &quot;LogPath&quot;: &quot;/var/lib/docker/containers/81b1ef821f70efb26990934d3f2f242912df0df03d6bd6d77b33c5f64c93dbe1/81b1ef821f70efb26990934d3f2f242912df0df03d6bd6d77b33c5f64c93dbe1-json.log&quot;,<br>        &quot;Name&quot;: &quot;/admiring_elion&quot;,<br>        ....<br>    }<br>]</pre><p>docker attach &lt;containerID&gt;: Enter to the attach local standard input, output, and error streams to a running container.</p><pre># For example:<br>$ docker attach 81b1ef821f70<br>#if you have write a loop print function in os, it will show in here.</pre><p><strong><em>Difference between </em></strong><strong><em>docker exec and </em></strong><strong><em>docker attach:</em></strong></p><ul><li>docker attach: Enter to the container that running the terminal, it will not create a new process 进程.</li><li>docker exec: Enter to the container and create a new terminal, and you can do your operation inside here (common use)</li></ul><p>docker cp &lt;containerID&gt;:&lt;containerFilePath&gt; &lt;copyToHostPath&gt;: copy the files from the container to your Linux (wsl, etc.)</p><pre># check the running container<br>root@jielim36:/home/jielim36# docker ps<br>CONTAINER ID   IMAGE     COMMAND   CREATED        STATUS        PORTS     NAMES<br>81b1ef821f70   debian    &quot;bash&quot;    19 hours ago   Up 15 hours             admiring_elion</pre><h3>Case 1: How to deploy Nginx</h3><ol><li>Search nginx image</li></ol><pre># search nginx<br>root@jielim36:/home/jielim36# docker search --limit 5 nginx<br>NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED<br>nginx                             Official build of Nginx.                        19471     [OK]<br>unit                              Official build of NGINX Unit: Universal Web …   20        [OK]<br>nginxinc/nginx-unprivileged       Unprivileged NGINX Dockerfiles                  140<br>nginx/nginx-ingress               NGINX and  NGINX Plus Ingress Controllers fo…   87<br>nginx/nginx-prometheus-exporter   NGINX Prometheus Exporter for NGINX and NGIN…   33</pre><p>2. Download image</p><pre>root@jielim36:/home/jielim36# docker pull nginx<br><br># Result<br>Using default tag: latest<br>latest: Pulling from library/nginx<br>2f44b7a888fa: Pull complete<br>8b7dd3ed1dc3: Pull complete<br>35497dd96569: Pull complete<br>36664b6ce66b: Pull complete<br>2d455521f76c: Pull complete<br>dc9c4fdb83d6: Pull complete<br>8056d2bcf3b6: Pull complete<br>Digest: sha256:4c0fdaa8b6341bfdeca5f18f7837462c80cff90527ee35ef185571e1c327beac<br>Status: Downloaded newer image for nginx:latest<br>docker.io/library/nginx:latest</pre><p>3. Create a container by nginx image</p><pre>#create a nginx container called &quot;nginx-server&quot;, and the port number is wsl 3344 and container port number 80. And, its run in background first (-d optional)<br>root@jielim36:/home/jielim36# docker run --name nginx-server -d -p 3344:80 nginx<br>097def652569511f245d2763c3368513a4f938163ee04a9c50558f9a14b098ea<br>root@jielim36:/home/jielim36# docker ps<br>CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS<br>           NAMES<br>097def652569   nginx     &quot;/docker-entrypoint.…&quot;   4 seconds ago   Up 3 seconds   0.0.0.0:3344-&gt;80/tcp, :::3344-&gt;80/tcp   nginx-server</pre><p>4. Send request to nginx container</p><pre># Now, we using curl send a request to our 3344 port number, and we can check the Nginx is work or not.<br># If success, it will return the HTML code<br>root@jielim36:/home/jielim36# curl localhost:3344<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>&lt;title&gt;Welcome to nginx!&lt;/title&gt;<br>&lt;style&gt;<br>html { color-scheme: light dark; }<br>body { width: 35em; margin: 0 auto;<br>font-family: Tahoma, Verdana, Arial, sans-serif; }<br>&lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Welcome to nginx!&lt;/h1&gt;<br>&lt;p&gt;If you see this page, the nginx web server is successfully installed and<br>working. Further configuration is required.&lt;/p&gt;&lt;p&gt;For online documentation and support please refer to<br>&lt;a href=&quot;http://nginx.org/&quot;&gt;nginx.org&lt;/a&gt;.&lt;br/&gt;<br>Commercial support is available at<br>&lt;a href=&quot;http://nginx.com/&quot;&gt;nginx.com&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;&lt;em&gt;Thank you for using nginx.&lt;/em&gt;&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Or you can access the docker container in your browser.</p><pre># Access in browser<br>$ ip addr # take the eth0&#39;s ip address, for example: 172.30.104.145<br>1: lo: &lt;LOOPBACK,UP,LOWER_UP&gt; mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000<br>    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00<br>    inet 127.0.0.1/8 scope host lo<br>       valid_lft forever preferred_lft forever<br>    inet6 ::1/128 scope host<br>       valid_lft forever preferred_lft forever<br>2: eth0: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1492 qdisc mq state UP group default qlen 1000<br>    link/ether 00:15:5d:34:5e:17 brd ff:ff:ff:ff:ff:ff<br>    inet 172.30.104.145/20 brd 172.30.111.255 scope global eth0 # take it<br>       valid_lft forever preferred_lft forever<br>    inet6 fe80::215:5dff:fe34:5e17/64 scope link<br><br># Access in browser: &lt;ip_address&gt;:&lt;container_portnumber&gt;<br># Example: 172.30.104.145:3344</pre><h3>Case 2: Deploy Tomcat</h3><pre># run the tomcat image, if the tomcat image is not download, it will automatic downlaod<br># --rm : Use for testing, when you end this container, it will automatic delete<br>$ docker run -it --rm -p 8888:8080 tomcat:9.0<br><br>Result:<br>root@jielim36:/home/jielim36# docker run -it --rm -p 8888:8080 tomcat:9.0<br>Unable to find image &#39;tomcat:9.0&#39; locally   # we have no download tomcat image<br>9.0: Pulling from library/tomcat            # automatic download<br>3dd181f9be59: Pull complete<br>0f838805bddf: Pull complete<br>e39426fdaf82: Pull complete<br>646f6a954707: Pull complete<br>7ad7501a603a: Pull complete<br>9a85227543ee: Pull complete<br>ca8673f71d67: Pull complete<br>ecf5872f0a18: Pull complete<br><br># Tomcat service start<br>Digest: sha256:cf71cbf54faf9f449bf89c8d6e861e8890dcd2083c6aba68e055ef536c591863<br>Status: Downloaded newer image for tomcat:9.0<br>Using CATALINA_BASE:   /usr/local/tomcat<br>Using CATALINA_HOME:   /usr/local/tomcat<br>Using CATALINA_TMPDIR: /usr/local/tomcat/temp<br>Using JRE_HOME:        /opt/java/openjdk<br>Using CLASSPATH:       /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar<br>Using CATALINA_OPTS:<br>NOTE: Picked up JDK_JAVA_OPTIONS:  --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.util.concurrent=ALL-UNNAMED --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED<br>13-Jan-2024 03:24:59.023 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version name:   Apache Tomcat/9.0.85<br>...<br>13-Jan-2024 03:24:59.434 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in [51] milliseconds<br><br># Inside Tomcat, you need to copy webapps.dist folder&#39;s file to the webapps folder.<br>$ cp -r webapps.dist/* webapps</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=934cc6a2a49d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Time Complexity in Algorithms?]]></title>
            <link>https://medium.com/@jielim36/what-is-time-complexity-in-algorithms-b99d9cf94f72?source=rss-5c85604199dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b99d9cf94f72</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Lim Yee Jie]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 11:31:58 GMT</pubDate>
            <atom:updated>2023-11-05T12:01:30.635Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Time Complexity in Algorithms?</h3><p>The time complexity of an algorithm quantifies the <strong>amount of time taken by an algorithm</strong> to run as a function of the length of the input.</p><p>In fact, the <strong>execution time of an algorithm is different on different machines</strong>. However, the <strong>number of executions of that algorithm is the same</strong> on different machines, so we actually <strong>measure the runtime of the algorithm by the number of executions of the statement</strong>.</p><p>When we learn about Time Complexity, we should know <strong>what is Input Size / Data Size</strong>?</p><p>Input size is generally a parameter in an algorithm that indicates the amount of data in this algorithm.</p><p>The input size can be an integer. This method gets an integer variable, its value can be 100,1000 or 100¹⁰.</p><pre>public long sum(int n){//send a integer data <br>    long res = 0;<br>    int i = 0;</pre><pre>    for(; i &lt;= n ; i++){<br>        res += i;<br>    }<br>    return res;<br>}</pre><ol><li>The input size can be an array, we using n to represent this value.</li></ol><pre>public long sum(int [] nums){//send an array <br>    long res = 0;<br>    int i = 0;</pre><pre>    int n = nums.length;<br>    for(; i &lt;= n ; i++){<br>        res += i;<br>    }<br>    return res;<br>}</pre><h3>How to calculate Time Complexity?</h3><p><strong>T(n)</strong> represents the number of executions of the program.</p><h3>Case 1:</h3><pre>public int method(){<br>	System.out.println(&quot;hello&quot;); //1 times<br>	return 0;			//1 times<br>    //result = 1+1 =2<br>}</pre><p>Times: <strong>T(n) = 2</strong> (Constant value)</p><p>We can change it into Big O notation: <strong>O(1)</strong></p><blockquote><em>if T(n) is a constant value, the Time Complexity is O(1).<br>if T(n) is a non-constant, the Time Complexity is O(n).</em></blockquote><h3>Case 2: Normal Loop</h3><p>We try to calculate the execution times of each line in this code.</p><pre>public int method(int n){<br>        for(int i = 0; i&lt;n ; i++){<br>         //i = 0 :1 times<br>         //i&lt;n :n+1 times <br>         //i++ : n times<br>            System.out.println(&quot;hello&quot;); //n times<br>        }<br>        return 1; //1 times<br>        //result : 1 + n+1 + n + n + 1 = 3n+3<br>    }</pre><p>In this case, we get the execution times is T(n) = 3n + 3, the final result of Time Complexity is O(n).</p><p>It is because in Big O notation, we typically focus on the algorithm’s asymptotic complexity, where <strong>constant coefficients and lower-order terms are disregarded</strong>, <strong>retaining only the fastest-growing term</strong> to denote the algorithm’s complexity.</p><blockquote><em>T(3n+3) = O(n)</em></blockquote><p>The coefficients and constants have very little effect on the increasing trend of execution time as the data size n continues to grow.</p><p>Example:</p><pre>n       n+3<br>1       3<br>10      13<br>100     103<br>1000    1003<br>10000   10003<br>...</pre><h3>Case 3: Nested Loop</h3><pre>public void method(int n){<br>   for(int i = 0; i &lt; n ; i++){ //1 times ; n+1 times ; n times<br>        for(int j = 0 ; j &lt; i ; j ++){<br>            //int j = 0 : 1*n = n times<br>            // j &lt; i : n*n times = n^2 times<br>            //j++ : n*n times = n^2 times<br>            System.out.println(&quot;a&quot;);//n^2 times<br>        }<br>    }<br>    //first loop: 1 + n+1 + n = 2n + 1<br>    //second loop: n + n^2 + n^2 + n^2 = 3n^2 + n<br>    //result : T(n) = 3n^2 + 3n + 1<br>}</pre><p>T(n) = 3n² + 3n + 1<br>Time Complexity = O(n²) , remember retaining only the fastest-growing term to denote the algorithm’s complexity.</p><blockquote><em>Tips: The most executed line of code represents the time complexity.</em></blockquote><p>In this case, System.out.println(&quot;a&quot;); is the most executed count of code, and it is n^2 times, so the result of this algorithms is O(n^2)</p><p>Another Case</p><pre>public void method(int n){<br>   for(int i = 0; i &lt; n ; i++){<br>        for(int j = 0 ; j &lt; i ; j ++){<br>            for(int j = 0 ; j &lt; i ; j ++){<br>                System.out.println(&quot;a&quot;);//most executed code: n^3 times<br>            }<br>        }<br>    }<br>}</pre><p>Time complexity: O(n^3)</p><h3>Case 4:</h3><pre>public void method(int n){<br>    int i = 1;<br>	while(i&lt;n)<br>	{<br>	    i = i * 2;<br>	}<br>}</pre><p>OR</p><pre>public void method(int n){<br>    for(int i = 1 ; i &lt; n ; i += i){<br>        System.out.println(&quot;Jielim36&quot;);//most executed code: log n<br>    }<br>}</pre><p>In both cases, the time complexity is O(log n). Because the executed times of this code is depend by the value of i, and the variable of i is increasing by `i += i, it means:</p><pre>first times: i = 1      i - 2^(1-1)=2^0<br>second times: i = 2     i - 2^(2-1)=2^1<br>third times: i = 3      i - 2^(3-1)=2^2<br>...<br>x times: i = x          i - 2(x-1)</pre><p>i — 2(x-1) means i &lt;= n, so 2^(x-1) &lt;= n<br>result:<br>x = 1 + log2n<br>time complexity = O(log n)</p><h3>Case 5:</h3><pre>public void method(int n) {<br>    for (int i = 1; m &lt; n; i++) {<br>        int i = 1;<br>        while (i &lt; n) {<br>            i = i * 2;<br>        }<br>    }<br>}</pre><p>In this case, i = i * 2 is still O(log n), but it is nested in a while loop, so the final result is O(n log n).</p><h3>Case 6:</h3><pre>for(int i = 0 ; i &lt; 10000 ; i++){<br>    System.out.println(&quot;jielim&quot;);<br>}</pre><p>In this case, the input size is a constant value 10000, so the result is O(1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*_uPlFDmvDksJGXT7.jpg" /></figure><p>As the size of n (input size) grows, the ranking of the growth rate of each data type in terms of time complexity:</p><ol><li>log n (Slowest)</li><li>n</li><li>O(n)</li><li>O(n^2) (Fastest)</li></ol><p>Using Time Complexity to measure algorithm performance is:</p><ol><li>O(1) (Best Performance)</li><li>log n</li><li>O(n)</li><li>O(n^2) (Bad Performance)</li></ol><h3>Compare the impact of different algorithms</h3><p>let say there are two algorithms which are:</p><ol><li>T(n) = 100n : Time Complexity = O(n)</li><li>T(n) = 5n^2 : Time Complexity = O(n^2)</li></ol><p>Algorithm A runs on an old computer and Algorithm B runs on some supercomputer that runs 100 times faster than the old computer.</p><p>So, as the input size n grows, who of the two algorithms runs faster?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*-MoEohMm5HkC1E3IqQ6LVQ.png" /></figure><p>According to the graph above, you can see that the first algorithm is <strong>slower than</strong> the second algorithm when the data size n is 1000. But when n reaches 10000, the execution speed of the second algorithm suddenly <strong>grows faster</strong> than the first algorithm. Based on this example, hopefully you can understand the impact of data size on an algorithm.</p><p>If you want to compare two algorithms who is better, you can also access <a href="https://www.desmos.com/calculator?lang=en-US">this website</a> to input your formula.</p><p>In this case, we compare the algorithms :</p><ol><li>Normal traverse an array(Linear Search):</li></ol><pre>public int linearSearch(int [] array , int target){<br>        for (int i = 0 ; i &lt; array.length ; i++){//1 + n+1 + n<br>            if (array[i] == target){//n<br>                return i;//return index<br>            }<br>        }<br>        return -1;//1<br>        //result : 1 + n+1 + n + n + 1 = 3n + 3<br>    }</pre><p>Time: T(n) = 3n+3</p><ol><li>Normal Binary Search Algorithm</li></ol><pre>public static int binarySearchEnhanced(int [] array , int target){<br>        int i = 0 , j = array.length;//1 + 1<br>        while (i &lt; j){//log<br>            int m = (i+j) &gt;&gt;&gt; 1;//log<br>            if (target &lt; array[m]){//log<br>                j  = m;<br>            }else if (array[m] &lt; target){//log<br>                i = m+1;//log<br>            }else{<br>                return m;<br>            }<br>        }<br>        return -1;<br>    }</pre><p>calculate log:<br>Assume n is <strong>4</strong> and all is executed else if (array[m] &lt; target)<strong>(slowest case)</strong>,so the while loop execution times is <strong>3</strong>. (You can put a variable inside the loop to calculate the executions times)<br>If we try to assume more n size, the result is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*fjWaXte60_SvOjr9tduvsw.png" /></figure><p>Input Size(n)Loop TimesFormula4–73Log2(4) = 28–154Log2(8) = 316–315Log2(16) = 432–636Log2(32) = 5</p><blockquote>1. The Formula such as Log2(4) = 2, when it <strong>plus 1</strong> will be equal loop times. Result: ((floor(Log2n) +1)) = Loop Times</blockquote><blockquote>2. (If n is a odd number such as 15, the result will be a float number that 4 &gt; result &lt; 5, we directly take the number of 3 ) , you can convert the formula to : floor(Log2(15) = 3)</blockquote><p>Calculate execution times:</p><ol><li>int i = 0 , j = array.length; : 1+1</li><li>while (i &lt; j) : L+1</li><li>int m = (i+j) &gt;&gt;&gt; 1; : L</li><li>if (target &lt; array[m]) : L</li><li>else if (array[m] &lt; target) : L</li><li>i = m+1; : L</li><li>return -1; : 1<br>Result:<br>5L + 3<br>Time: T(n) = (floor(Log2n) +1)*5 + 4</li></ol><p><strong>Now we can compare the execution times between linear search and binary search.</strong></p><ol><li><strong>Assume </strong><strong>n = 4:</strong></li></ol><p>Linear search :<br>= 3(n) +3<br>= 3(4) +3<br>= 15 times (Fast)</p><p>Binary Search:<br>= (floor(Log2n) +1)*5 + 4<br>= (floor(Log24) +1)*5 + 4<br>= (2+1)*5 +4<br>= 19 times (Slow)</p><ol><li><strong>Assume </strong><strong>n = 1024:</strong><br>= 3(n) +3<br>= 3(1024) +3<br>= 3075 times (Slow)</li></ol><p>Binary Search:<br>= (floor(Log2n) +1)*5 + 4<br>= (floor(Log21024) +1)*5 + 4<br>= (10+1)*5 +4<br>= 59 times (Fast)</p><p>If you want to know how the two algorithms change when n grows extremely fast, check out <a href="https://www.desmos.com/calculator?lang=en-US">this site</a>.</p><p>You can input your time complexity formula into left side (change n into x):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*EJKybg3MGLwuiVPLLP-9HA.png" /></figure><p>After that, you can see what happens to the value of y (execution times), when value of x (input size n) is increasing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PK_BpgXOwCEcgFThnUBixA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b99d9cf94f72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Design Pattern — Builder Pattern]]></title>
            <link>https://medium.com/@jielim36/understanding-design-pattern-builder-pattern-4a507a863785?source=rss-5c85604199dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a507a863785</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Lim Yee Jie]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 13:03:53 GMT</pubDate>
            <atom:updated>2023-11-02T13:03:53.259Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Design Pattern — Builder Pattern</h3><h3>Builder Design Pattern</h3><p>Builder Design Pattern can separate the construction of a complex object from its representation so that the same construction process can create different representations.</p><h3>Builder Design Pattern Type Two</h3><p>In real case, there are many component which are RAM,CPU,Fans,and Graphic Card to build a computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*yMkDXjZrhwXjnK6g" /></figure><p>Structure:<br>Product: The complex object we want to create.<br>Builder: This abstract base class efines all of the steps that must be taken in order to correctly create a product.<br>ConcreteBuilder: Implement Builder interface,</p><p>Product: Computer class</p><pre>public class Computer {<br>    private String Ram;<br>    private String Cpu;<br>    //getter and setter<br>    @Override<br>    public String toString() {<br>        return &quot;Computer{&quot; +<br>                &quot;Ram=&#39;&quot; + Ram + &#39;\&#39;&#39; +<br>                &quot;, Cpu=&#39;&quot; + Cpu + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }<br>}</pre><p>Builder class:</p><pre>public abstract class Builder {<br>    protected Computer computer = new Computer();<br>    public abstract void buildRam();<br>    public abstract void buildCpu();<br>    public abstract Computer createComputer();<br>}</pre><p>Concrete Builder: AsusComputerBuilder and AcerComputerBuilder</p><pre>public class AcerComputerBuilder extends Builder{<br>    @Override<br>    public void buildRam() {<br>        computer.setRam(&quot;(Acer) 8GB RAM&quot;);<br>    }<br>    @Override<br>    public void buildCpu() {<br>        computer.setCpu(&quot;(Acer) AMD CPU&quot;);<br>    }<br>    @Override<br>    public Computer createComputer() {<br>        return computer;<br>    }<br>}</pre><pre>public class AsusComputerBuilder extends Builder{<br>    @Override<br>    public void buildRam() {<br>        computer.setRam(&quot;(Asus) 16GB RAM&quot;);<br>    }<br>    @Override<br>    public void buildCpu() {<br>        computer.setCpu(&quot;(Asus) Intel CPU&quot;);<br>    }<br>    @Override<br>    public Computer createComputer() {<br>        return computer;<br>    }<br>}</pre><p>Director:</p><pre>public class Director {<br>    private Builder builder;<br>    public Director(Builder builder){<br>        this.builder = builder;<br>    }<br>    public Computer construct(){<br>        builder.buildRam();<br>        builder.buildCpu();<br>        return builder.computer;<br>    }<br>}</pre><p>Usage:</p><pre>public class Client {<br>    public static void main(String[] args) {<br>        Director director = new Director(new AsusComputerBuilder());<br>        Computer computer = director.construct();<br>        System.out.println(computer);//toString()<br>    }<br>}</pre><pre>Output:<br>Computer{Ram=&#39;(Asus) 16GB RAM&#39;, Cpu=&#39;(Asus) Intel CPU&#39;}</pre><p>In this case, Computer abstract class defined what component need, Builder abstract class defined the method for build computer component. After that, we can create the different type of computer into a concrete builder class such as AsusComputerBuilder and AcerComputerBuilder, and implement the method that Builder abstract class defined. Finally, we need the Director class to create a complete computer using builder, and the usage is send a concrete builder that we declared into the Director constructor.</p><h3>Builder Design Pattern Type Two</h3><p>When a class’s constructor requires many parameters, the readability of the class is poor and it is easy to make typing errors. In this case, we can use the Builder Pattern for refactoring.</p><h3>Before</h3><pre>public class Computer {<br>    private String cpu;<br>    private String ram;<br>    private String storage;<br>    private String brand;<br>    public Computer(String cpu, String ram, String storage, String brand) {<br>        this.cpu = cpu;<br>        this.ram = ram;<br>        this.storage = storage;<br>        this.brand = brand;<br>    }<br>    //getter and setter<br>    @Override<br>    public String toString() {<br>        return &quot;Phone{&quot; +<br>                &quot;cpu=&#39;&quot; + cpu + &#39;\&#39;&#39; +<br>                &quot;, ram=&#39;&quot; + ram + &#39;\&#39;&#39; +<br>                &quot;, storage=&#39;&quot; + storage + &#39;\&#39;&#39; +<br>                &quot;, brand=&#39;&quot; + brand + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }<br>}</pre><p>Usage:</p><pre>public static void main(String[] args) {<br>        Computer computer = new Computer(&quot;Intel&quot;,&quot;Kingston 8GB&quot;,&quot;WD SSD 500GB&quot;,&quot;Asus&quot;);<br>        System.out.println(computer);<br>        //Output: Phone{cpu=&#39;Intel&#39;, ram=&#39;Kingston 8GB&#39;, storage=&#39;WD SSD 500GB&#39;, brand=&#39;Asus&#39;}<br>}</pre><h3>After</h3><pre>public class Computer {<br>    private String cpu;<br>    private String ram;<br>    private String storage;<br>    private String brand;<br><br>    private Computer(Builder builder) {<br>        this.cpu = builder.cpu;<br>        this.ram = builder.ram;<br>        this.storage = builder.storage;<br>        this.brand = builder.brand;<br>    }<br><br>    public static final class Builder{<br>        private String cpu;<br>        private String ram;<br>        private String storage;<br>        private String brand;<br>        public Builder cpu(String cpu){<br>            this.cpu = cpu;<br>            return this;//return builder<br>        }<br>        public Builder ram(String ram){<br>            this.ram = ram;<br>            return this;<br>        }<br>        public Builder storage(String storage){<br>            this.storage = storage;<br>            return this;<br>        }<br>        public Builder brand(String brand){<br>            this.brand = brand;<br>            return this;<br>        }<br>        public Computer build(){<br>            return new Computer(this);<br>        }<br>    }<br>    @Override<br>    public String toString() {<br>        return &quot;Computer{&quot; +<br>                &quot;cpu=&#39;&quot; + cpu + &#39;\&#39;&#39; +<br>                &quot;, ram=&#39;&quot; + ram + &#39;\&#39;&#39; +<br>                &quot;, storage=&#39;&quot; + storage + &#39;\&#39;&#39; +<br>                &quot;, brand=&#39;&quot; + brand + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }<br>}</pre><p>Usage:</p><pre>public static void main(String[] args) {<br>        Computer computer =  new Computer.Builder() //create a Builder class to call builder&#39;s method<br>                .cpu(&quot;Intel&quot;) //set the data of cpu and return back Builder class using &quot;this&quot; keyword<br>                .ram(&quot;Kingston 8GB&quot;)//ram can be call after invoke cpu() method because cpu() method return Builder class &quot;this&quot; keyword.<br>                .storage(&quot;WD SSD 500GB&quot;)<br>                .brand(&quot;Asus&quot;)<br>                .build();//invoke build() to call the Computer&#39;s private constructor to create a Computer object<br>        System.out.println(computer);//Computer{cpu=&#39;Intel&#39;, ram=&#39;Kingston 8GB&#39;, storage=&#39;WD SSD 500GB&#39;, brand=&#39;Asus&#39;}<br>    }</pre><p>In this case, we modify the Computer&#39;s constructor into private access modifier, and using Builder inner class to build each component and call the build() method to create a Computer object.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a507a863785" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Design Pattern — Factor Method]]></title>
            <link>https://medium.com/@jielim36/understanding-design-pattern-factor-method-4ddb4f30e332?source=rss-5c85604199dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ddb4f30e332</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Lim Yee Jie]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 10:31:38 GMT</pubDate>
            <atom:updated>2023-11-01T10:31:38.631Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Design Pattern — Factor Method</h3><h3>Creational — Factory Method</h3><h3>Before using Factory Method</h3><p>Example: Cafe produce coffee</p><pre>public abstract class Coffee {<br>    String name;<br>    <br>    public void addSugar(){<br>        System.out.println(&quot;Add Sugar!!&quot;);<br>    }<br>    public void addMilk(){<br>        System.out.println(&quot;Add Milk!!&quot;);<br>    }<br>    public String getName() {<br>        return name;<br>    }<br>    public void setName(String name) {<br>        this.name = name;<br>    }<br>}</pre><pre>public class LatteCoffee extends Coffee{<br>    @Override<br>    public String getName() {<br>        return &quot;Latte Coffee&quot;;<br>    }<br>}</pre><pre>public class AmericanoCoffee extends Coffee{<br>    @Override<br>    public String getName() {<br>        return &quot;Americano Coffee&quot;;<br>    }<br>}</pre><pre>public class Cafe {<br>    public Coffee orderCoffee(String type){<br>        Coffee coffee = null;<br>        if (type.equals(&quot;Americano Coffee&quot;)){<br>            coffee = new AmericanoCoffee();<br>        } else if (type.equals(&quot;Latte Coffee&quot;)) {<br>            coffee = new AmericanoCoffee();<br>        }else {<br>            throw new RuntimeException(&quot;Invalid type of coffee!!&quot;);<br>        }<br>        coffee.addMilk();<br>        coffee.addSugar();<br>        return coffee;<br>    }<br>}</pre><pre>public static void main(String[] args) {<br>        Cafe cafe = new Cafe();<br>        Coffee coffee = cafe.orderCoffee(&quot;Latte Coffee&quot;);<br>        System.out.println(&quot;My Coffe: &quot; + <br>}</pre><p>In this case, we have a superclass called Coffee and if we want to create a new type of coffee we may add a subclass below it such as AmericanCoffee and LatteCoffee.</p><p>The problem of it is in the Cafe class, orderCoffee() method using if-else statement to verify the type of coffee and produce the specific coffee and return it. If we add a new coffee type called MochaCoffee, we must add a new if-else statement in the orderCoffee() method to verify this new coffee. It is violating the software design principles called <strong>Open/Closed Principle</strong>.</p><p>If we want to resolve this problem, we should using <strong>Factory Method.</strong> There are three factory method type:</p><ol><li>Simple Factory Method</li><li>Factory Method</li><li>Abstract Factory</li></ol><h3>1. Simple Factory Method</h3><p>Simple Factory is not a design pattern, but more of a programming style.</p><p>Structure:</p><ul><li>Abstract Product: Defined the rules of the product, describe the characteristic and functionality of the product.</li><li>Concrete Product: The subclass that implement or inherit the abstract product.</li><li>Concrete Factory: Provide the ways to producing products, we get the product through this method.</li></ul><p>Resolve:<br>We don’t change anything in Coffee abstract class and its subclass. We add a new class called SimpleCoffeFactory.</p><pre>public class SimpleCoffeeFactory {<br>        public Coffee createCoffee(String type){<br>        Coffee coffee = null;<br>        if (type.equals(&quot;Americano Coffee&quot;)){<br>            coffee = new AmericanoCoffee();<br>        } else if (type.equals(&quot;Latte Coffee&quot;)) {<br>            coffee = new AmericanoCoffee();<br>        }else {<br>            throw new RuntimeException(&quot;Invalid type of coffee!!&quot;);<br>        }<br>        return coffee;<br>    }<br>}</pre><pre>public class Cafe {<br>    public Coffee orderCoffee(String type){<br>        SimpleCoffeeFactory simpleCoffeeFactory = new SimpleCoffeeFactory();<br>        Coffee coffee = simpleCoffeeFactory.createCoffee(type);<br>        coffee.addSugar();<br>        coffee.addMilk();<br>        return coffee;<br>    }<br>}</pre><p>We create a new class called SimpleCoffeeFactory, give class SimpleCoffeeFactory the job of creating the coffee object that was originally given to class Cafe, so that all responsibility of these class is cleary, but its also not resolve the problem of <strong>Open/Closed Principle</strong> and we should using <strong>Factory Method</strong> design pattern to solve it.</p><h3>2. Factory Method</h3><p>Concept: Defined a interface that use for create object, let the subclass decide which type of coffee to instantiate.<strong>The factory method delays the instantiation of a product class to its factory subclass.</strong></p><p>Structure:</p><ul><li><strong>Abstract Factory:</strong> Provide the interface to create products, we can access its specific factory to create products.</li><li><strong>Concrete Factory:</strong> Subclasses of the Creator implement the Factory Method to create specific instances of the Product. Each subclass is responsible for instantiating a particular type of Product</li><li><strong>Abstract Product:</strong> Defined the rules of the product, describe the characteristic and functionality of the product.</li><li><strong>Concrete Product:</strong> Implement the specific functionality of the abstract product. <strong>The relationship between Concrete Product and Concrete Factory is One to One.</strong></li></ul><p>Abstract Factory:</p><pre>public interface CoffeeFactory {<br>    Coffee createCoffee();<br>}</pre><p>Concrete Factory : LatteCoffeeFactory and AmericanoCoffeeFactory.</p><pre>public class LatteCoffeeFactory implements CoffeeFactory{<br>    @Override<br>    public Coffee createCoffee() {<br>        return new LatteCoffee();<br>    }<br>}</pre><pre>public class AmericanoCoffeeFactory implements CoffeeFactory{<br>    @Override<br>    public Coffee createCoffee() {<br>        return new AmericanoCoffee();<br>    }<br>}</pre><p>Abstract Product:</p><pre>public abstract class Coffee {<br>    String name;<br>    public void addSugar(){<br>        System.out.println(&quot;Add Sugar!!&quot;);<br>    }<br>    public void addMilk(){<br>        System.out.println(&quot;Add Milk!!&quot;);<br>    }<br>    public String getName() {<br>        return name;<br>    }<br>    public void setName(String name) {<br>        this.name = name;<br>    }<br>}</pre><p>Concrete Product: AmericanoCoffee and LatteCoffee.</p><pre>public class LatteCoffee extends Coffee {<br>    @Override<br>    public String getName() {<br>        return &quot;Latte Coffee&quot;;<br>    }<br>}</pre><pre>public class AmericanoCoffee extends Coffee {<br>    @Override<br>    public String getName() {<br>        return &quot;Americano Coffee&quot;;<br>    }<br>}</pre><p>Centre:</p><pre>public class Cafe {<br>    private CoffeeFactory coffeeFactory;<br>    public void setCoffeeFactory(CoffeeFactory coffeeFactory){<br>        this.coffeeFactory = coffeeFactory;<br>    }<br>    public Coffee orderCoffee(){<br>        Coffee coffee = coffeeFactory.createCoffee();<br>        coffee.addSugar();<br>        coffee.addMilk();<br>        return coffee;<br>    }<br>}</pre><p>Usage:</p><pre>public class Test {<br>    public static void main(String[] args) {<br>        Cafe cafe = new Cafe();<br>        CoffeeFactory factory = new AmericanoCoffeeFactory();<br>        cafe.setCoffeeFactory(factory);//input the specific factory to produce a specific coffee<br>        Coffee coffee = cafe.orderCoffee();<br>        System.out.println(&quot;My Coffee:&quot;+coffee.getName());<br>    }<br>}</pre><p>In this case, we solve the problem of <strong>Open/Closed Principle</strong>, because if we want to create a new type of coffee called MochaCoffee, we can directly create a new concrete product class called MochaCoffee and concrete factory class called MochaCoffeeFactory class, and <strong>we don&#39;t even need to change any existing code</strong> like Cafe class. However, the <strong>disadvantages of the factory method</strong> is that there are so many classes we need to declare, which increases the complexity of the system.</p><h3>Abstract Factory</h3><p>Suppose our cafe now sells Coffee and Cake products, and we have TiramisuCake and MatchaCake, if we continued to use the factory method, we would have too many classes in our system.</p><p>Now let’s analyse our products, now I have AmericanoCoffee, LatteCoffee, TiramisuCake, and MatchaCake. We can categorize them into product categories called Coffee and Cake, and flavour types called AmericanFlavour and ItalianFlavour.</p><p>Structure:</p><ul><li><strong>Abstract Factory:</strong> Provide the interface of create products, it can create many type of product such as Coffee and Cake.</li><li><strong>Concrete Factory:</strong> Implement abstract factory, create the specific type of products.</li><li><strong>Abstract Product:</strong> Defined products, describe the features and function of the products.</li><li><strong>Concrete Product:</strong> Implement abstract product, instance create by concrete factory, <strong>the relationship between concrete product and concrete factory is Many to One.</strong></li></ul><p>Abstract Product: Coffee and Cake</p><pre>public abstract class Cake {<br>    public abstract void show();<br>}</pre><pre>public abstract class Coffee {<br>    String name;<br>    <br>    public String getName() {<br>        return name;<br>    }<br>    public void setName(String name) {<br>        this.name = name;<br>    }<br>}</pre><p>Concrete Product: AmericanoCoffee, LatteCoffee, MatchaCake, and TiramisuCake.</p><pre>public class AmericanoCoffee extends Coffee {<br>    @Override<br>    public String getName() {<br>        return &quot;Americano Coffee&quot;;<br>    }<br>}</pre><pre>public class LatteCoffee extends Coffee {<br>    @Override<br>    public String getName() {<br>        return &quot;Latte Coffee&quot;;<br>    }<br>}</pre><pre>public class MatchaCake extends Cake{<br>    @Override<br>    public void show() {<br>        System.out.println(&quot;Matcha Cake&quot;);<br>    }<br>}</pre><pre>public class TiramisuCake extends Cake{<br>    @Override<br>    public void show() {<br>        System.out.println(&quot;Tiramisu Cake!&quot;);<br>    }<br>}</pre><p>Abstract Factory:</p><pre>public interface FlavourFactory {<br>    Coffee createCoffee();<br>    Cake createCake();<br>}</pre><p>Concrete Factory:</p><pre>public class ItalianFlavourFactory implements FlavourFactory{<br>    public Coffee createCoffee(){<br>        return new LatteCoffee();<br>    }<br>    public Cake createCake(){<br>        return new TiramisuCake();<br>    }<br>}</pre><pre>public class AmericanFlavourFactory implements FlavourFactory{<br>    public Coffee createCoffee(){<br>        return new AmericanoCoffee();<br>    }<br>    public Cake createCake(){<br>        return new MatchaCake();<br>    }<br>}</pre><p>Usage:</p><pre>public class Test {<br>    public static void main(String[] args) {<br>        AmericanFlavourFactory americanFlavourFactory = new AmericanFlavourFactory();<br>        Cake cake01 = americanFlavourFactory.createCake();<br>        Coffee coffee01 = americanFlavourFactory.createCoffee();<br>        cake01.show();<br>        System.out.println(coffee01.getName());<br>        System.out.println(&quot;===============&quot;);<br>        ItalianFlavourFactory italianFlavourFactory = new ItalianFlavourFactory();<br>        Cake cake02 = italianFlavourFactory.createCake();<br>        Coffee coffee02 = italianFlavourFactory.createCoffee();<br>        cake02.show();<br>        System.out.println(coffee02.getName());<br>    }<br>}</pre><pre>Output:<br>Matcha Cake<br>Americano Coffee<br>===============<br>Tiramisu Cake!<br>Latte Coffee</pre><p><strong>The disadvantages of Abstract Factory:</strong><br>If I want to add a new flavour called MalaysianFlavour, I can add the concrete factory called MalaysianFlavourFactory and the concrete product called AhHuatFlatWhiteCoffee. As you can see, when we add a new flavour we only need to add the new class without modifying the existing code.</p><p><strong>The disadvantages of Abstract Factory:</strong><br>If I want to add a new product called IceCream, all concrete factory class must modify the code because concrete factory need to add a interface for create IceCream instance.</p><p>Based on the above advantages and disadvantages, we need to <strong>analyse whether our product is fixed and flavour is variable before using Abstract Factory.</strong> Another example: There are only two products, laptops and mobile phones, but there are many brands.</p><h3>Factory Method with properties</h3><p>We can try to emulate the <strong>Spring IoC design pattern</strong> and create a Coffee class by writing the Concrete class path using the properties file.</p><p><strong>My File Structure:</strong><br>java:<br>-FactoryMethod_withProperties<br> — Coffee.java<br> — AmericanoCoffee.java<br> — LatteCoffee.java<br> — CoffeeFactory.java<br> — Test.java</p><p>resources:<br>-bean.properties (we write the path of the coffee concrete classes in this file)</p><pre>public abstract class Coffee {<br>    String name;<br>    public String getName() {<br>        return name;<br>    }<br>    public void setName(String name) {<br>        this.name = name;<br>    }<br>}</pre><pre>public class AmericanoCoffee extends Coffee {<br>    @Override<br>    public String getName() {<br>        return &quot;Americano Coffee&quot;;<br>    }<br>}</pre><pre>public class LatteCoffee extends Coffee {<br>    @Override<br>    public String getName() {<br>        return &quot;Latte Coffee&quot;;<br>    }<br>}</pre><p>Properties file: bean.properties</p><pre>americano=FactoryMethod_withProperties.AmericanoCoffee<br>latte=FactoryMethod_withProperties.LatteCoffee</pre><pre>public class CoffeeFactory {<br>    private static HashMap&lt;String,Coffee&gt; coffeeMap = new HashMap&lt;&gt;();<br>    static {<br>        Properties beanProperties = new Properties();<br>        InputStream resourceAsStream = CoffeeFactory.class.getClassLoader().getResourceAsStream(&quot;bean.properties&quot;);<br>        try {<br>            beanProperties.load(resourceAsStream);<br>            Set&lt;Object&gt; keys = beanProperties.keySet();<br>            for (Object key : keys){<br>                String className = beanProperties.getProperty((String) key);<br>                //className: americanoCoffee class path( FactoryMethod_withProperties.AmericanoCoffee )<br>                //use reflection to create class<br>                Class clazz = Class.forName(className);<br>                Coffee coffeeClass = (Coffee)clazz.newInstance();<br>                coffeeMap.put((String) key,coffeeClass);//key:value = americano:FactoryMethod_withProperties.AmericanoCoffee class<br>            }<br>        } catch (Exception e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br>    public static Coffee createCoffee(String name){<br>        return coffeeMap.get(name);<br>    }<br>}</pre><p>Usage:</p><pre>public class Test {<br>    public static void main(String[] args) {<br>        Coffee coffee = CoffeeFactory.createCoffee(&quot;latte&quot;);<br>        System.out.println(coffee.getName());//Output: Latte Coffee<br>    }<br>}</pre><p>In this case, we read all data from bean.properties into the Hash Map variable called coffeeMap. We called the createCoffee(String name) method and send the string data same with key value in bean.properties, so that we can get the concrete class that the path you write in bean.properties.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ddb4f30e332" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Prototype Design Pattern]]></title>
            <link>https://medium.com/@jielim36/understanding-prototype-design-pattern-a38b165de598?source=rss-5c85604199dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a38b165de598</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Lim Yee Jie]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 11:31:11 GMT</pubDate>
            <atom:updated>2023-10-31T11:31:11.893Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prototype Pattern</h3><p>The Prototype Pattern is a creational design pattern that allows you to copy an existing object into a new instances of objects while minimizing the coupling to the object creation process. There are two types of copying which are shallow copy and deep copy.</p><p><strong>Shallow Copy:</strong></p><ul><li>In shallow copy, only the object itself is copied, and the reference-type member objects within the object are not copied.</li><li>If the prototype object contains reference-type member variables, a shallow copy will duplicate references to these members rather than their content.</li><li>This means that if you modify the reference-type member objects within the prototype object, the cloned objects will also be affected because they share the same reference-type members.</li></ul><p><strong>Deep Copy:</strong></p><ul><li>In deep copy, not only is the object itself copied, but reference-type member objects are also recursively copied to ensure that the cloned object is completely independent from the original.</li><li>This means that regardless of how the reference-type member objects of the prototype object are modified, the cloned objects remain unaffected because they have their own independent reference-type members.</li></ul><p>Structure:</p><ol><li><strong>Abstract Prototype Class:</strong> provide the method that concrete prototype must implement such as clone() method.</li><li><strong>Concrete Prototype Class:</strong> Implement the method of abstract prototype class, concrete protype class can be copy.</li><li><strong>Usage Class:</strong> Using the clone() method of concrete prototype class to clone a new object.</li></ol><h3>Case One (Shallow Copy)</h3><p>Concrete Prototype Class is implement the Cloneable interface of JDK.</p><pre>public class ConcretePrototype implements Cloneable{<br>  private Student student;<br>    public ConcretePrototype() {<br>        System.out.println(&quot;ConcretePrototype constructor is called...&quot;);<br>    }<br>    @Override<br>    protected ConcretePrototype clone() throws CloneNotSupportedException {<br>        System.out.println(&quot;Cloning new object in clone() method...&quot;);<br>        return (ConcretePrototype) super.clone();<br>    }<br>    public void printInfo(){<br>        System.out.println(&quot;Hello World!!&quot;);<br>    }<br>    public Student getStudent() {<br>        return student;<br>    }<br>    public void setStudent(Student student) {<br>        this.student = student;<br>    }<br>}</pre><p>Variable in ConcretePrototype class.</p><pre>public class Student {<br>    private String name;<br>    public String getName() {<br>        return name;<br>    }<br>    public void setName(String name) {<br>        this.name = name;<br>    }<br>}</pre><p>Usage:</p><pre>public class Client {<br>    public static void main(String[] args) throws CloneNotSupportedException {<br>        ConcretePrototype existingObj = new ConcretePrototype();//constructor output: ConcretePrototype constructor is called...<br>        Student student = new Student();<br>        student.setName(&quot;Jielim36&quot;);<br>        existingObj.setStudent(student);<br>        ConcretePrototype cloneObj = existingObj.clone();<br>        cloneObj.printInfo();//output: Hello World!!<br>        cloneObj.getStudent().setName(&quot;Tommy&quot;);<br>        System.out.println(&quot;Object Same? : &quot; + (existingObj==cloneObj));//output: false<br>        System.out.println(&quot;Existing Object&#39;s student name:&quot; + existingObj.getStudent().getName());<br>        System.out.println(&quot;Clone Object&#39;s student name:&quot; + cloneObj.getStudent().getName());<br>        System.out.println(&quot;student name address Same? : &quot; + (existingObj.getStudent() == cloneObj.getStudent()));<br>    }<br>}</pre><pre>Output:<br>ConcretePrototype constructor is called...<br>Cloning new object in clone() method...<br>Hello World!!<br>Object Same? : false<br>Existing Object&#39;s student name:Tommy<br>Clone Object&#39;s student name:Tommy<br>student name address Same? : true</pre><p>Based on the output we can get the following information:</p><ul><li>When a we create a concrete prototype object will called the constructor and output a message “ConcretePrototype constructor is called…”. However, when we use the clone() method to create a object, the constructor is not executed.</li><li>If we compare the memory address between the existing object and clone object, the result will be false.</li><li>If we set the student name of the existing object previously, and we clone it and change the student name of the clone object. As you can see, the student name between both objects is change to the same name called “Tommy”, means that it is a <strong>shallow copy</strong> because we change the name of the clone object will be affected the existing object.</li><li>If we compare the variable memory address between the existing object and clone object, the result will be true, meaning that it is a <strong>shallow copy</strong>. Because the variable address of the cloned object is referenced to the variable address of the existing object.</li></ul><h3>Case Two (Deep Copy)</h3><p>How do we change the student name of clone object and not affected the student name of the existing object?</p><p>We implement Serializable interface in Student and ConcretePrototype class.</p><pre>public class ConcretePrototype implements Cloneable, Serializable {<br>    //code...<br>}</pre><pre>public class Student implements Serializable {<br>    //code...<br>}</pre><pre>public class Client {<br>    public static void main(String[] args) throws Exception {<br>        ConcretePrototype existingObj = new ConcretePrototype();//constructor output: ConcretePrototype constructor is called...<br>        Student student = new Student();<br>        student.setName(&quot;Jielim36&quot;);<br>        existingObj.setStudent(student);<br>        //write object<br>        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(&quot;myObject.txt&quot;));<br>        oos.writeObject(existingObj);<br>        oos.close();<br>        //read object<br>        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(&quot;myObject.txt&quot;));<br>        ConcretePrototype cloneObj = (ConcretePrototype) ois.readObject();<br>        ois.close();<br>        //change the student name of the readObject<br>        cloneObj.getStudent().setName(&quot;Tommy&quot;);<br>        System.out.println(&quot;Object Same? : &quot; + (existingObj==cloneObj));//output: false<br>        System.out.println(&quot;Existing Object&#39;s student name:&quot; + existingObj.getStudent().getName());<br>        System.out.println(&quot;Clone Object&#39;s student name:&quot; + cloneObj.getStudent().getName());<br>        System.out.println(&quot;student name address Same? : &quot; + (existingObj.getStudent() == cloneObj.getStudent()));<br>    }<br>}</pre><pre>Output:<br>ConcretePrototype constructor is called...<br>Object Same? : false<br>Existing Object&#39;s student name:Jielim36<br>Clone Object&#39;s student name:Tommy<br>student name address Same? : false</pre><p>In this case, we try to use write and read object with stream to clone a new object. After that, we can directly change the student name of the clone obejct and not affect the student name of the existing object anymore.</p><h3>Custom Prototype Pattern</h3><pre>public interface User {<br>    User clone();<br>}</pre><pre>public class Admin implements User {<br>    private String username;<br>    private Authority authority;<br>    public Admin(String username) {<br>        this.username = username;<br>    }<br>    @Override<br>    public Admin clone() {<br>        Admin admin = new Admin(this.getUsername());//create a new admin object and give it own data<br>        admin.setAuthority(this.getAuthority());<br>        return admin;<br>    }<br>    //getter and setter<br>}</pre><pre>public class Authority {<br>    private int level;<br>    private String description;<br>    public Authority(int level, String description) {<br>        this.level = level;<br>        this.description = description;<br>    }<br>    //getter and setter<br>}</pre><pre>public class Client {<br>    public static void main(String[] args) {<br>        Admin admin = new Admin(&quot;jielim36&quot;);<br>        admin.setAuthority(new Authority(1,&quot;Highest Authority&quot;));<br>        Admin cloneAdmin = admin.clone();<br>        cloneAdmin.getAuthority().setDescription(&quot;Lowest Authority&quot;);<br>        System.out.println(&quot;Existing Admin authority Description:&quot; + admin.getAuthority().getDescription());<br>        System.out.println(&quot;Clone Admin authority Description:&quot; + cloneAdmin.getAuthority().getDescription());<br>    }<br>}</pre><p>If you want to customize your own clone() method, you can create an object and pass your all value of the existing object to the new object, but it is <strong>shallow copy</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a38b165de598" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My first personal web application project]]></title>
            <link>https://medium.com/@jielim36/my-first-personal-web-application-project-cacb8833f569?source=rss-5c85604199dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/cacb8833f569</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Lim Yee Jie]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 08:44:40 GMT</pubDate>
            <atom:updated>2023-10-30T08:46:36.423Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Preface</strong></h3><p>Hello, I am currently pursuing a Diploma in Computer Science, and my journey in the world of programming has already crossed its first anniversary since my enrollment in September 2022.</p><p>Over the past year, my passion for creating my own software has only grown stronger. However, I had been missing the essential skills and knowledge required to develop my own projects. In pursuit of this dream, I delved into a comprehensive learning journey, immersing myself in various programming languages and technologies, with a primary focus on web development.</p><p>My learning journey has encompassed a wide array of technologies, including HTML, CSS, JavaScript, and React.js for front-end development. In addition, I expanded my horizons to the realm of back-end development, where I explored technologies such as Java and Java frameworks like SSM (Spring, Spring Security, MyBatis) and Spring Boot. This intensive learning not only broadened my skill set but also provided me with the competence to develop complete and sophisticated projects.</p><p>Before I learnt all this knowledge, I often found myself working on small programs that lacked a user-friendly interface, which left me feeling unsatisfied with the aesthetics of my creations. Now, with a well-rounded technical foundation, I am ready to translate my ideas into fully functional software.</p><h3><strong>Content</strong></h3><p>Creating my first web application project was a significant learning experience for me. This personal project allowed me to explore various aspects of web development and gain valuable insights into the world of software engineering. Below, I’ve outlined the key steps and lessons I learned during this exciting journey:</p><ol><li>Defining the Requirements:</li></ol><p>To kick off the project, the first step was to identify the theme and requirements. Since my primary goal was to learn, it was essential that the project encompass fundamental CRUD operations. This laid the foundation for my web application.</p><p>2. Planning:</p><p>Project planning involved defining the architecture, selecting the appropriate technology stack, and tools. As a student, I wanted to practice and enhance my skills in specific programming languages, emphasizing the learning aspect. I ultimately chose a front-end and back-end separation architecture using React.js and Java Spring Boot, respectively. My data interaction was facilitated by Mybatis and MySQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*eQDXXxjtMbpHZqhFo5CwvQ.png" /></figure><p>3. Front-End Development:</p><p>Front-end development was a challenging aspect for me, as I had limited experience in this area. However, my learning-oriented personal project motivated me to invest time in improving my front-end skills. Here’s what I did:</p><ul><li>I designed the user interface (UI) using pure CSS for visual design and animations.</li><li>I implemented the front-end logic using React.js.</li><li>HTTP requests were made using Ajax, Axios, and later, the <a href="https://tanstack.com/">TanStack</a> tools.</li><li>I researched and drew inspiration from websites like <a href="https://ant.design/docs/spec/introduce">Antd Design</a> to create my unique design style. I realized that simple color schemes and thematic accents could be effective, even for those not confident in web design.</li></ul><blockquote>Home Page</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gQtQc2PXnqtBA9aE" /></figure><blockquote>Article Publish Page</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hXhN-flyb2q6S7M2" /></figure><p>4. Back-End Development:</p><p>For back-end development, I utilized the Java framework Spring Boot. This part of the project allowed me to learn about designing effective REST APIs, handling JSON data from the front-end, and user authentication using Spring Security and JWT.</p><p>After successfully implementing these functionalities within a week, I paused my project for various reasons:</p><ul><li>My primary learning objectives had been met, and I had gained valuable experience in developing a complete software system, from the front end to the back end and the database, including basic CRUD operations.</li><li>Academic commitments had intensified due to ongoing coursework, which involved C++, Android Studio, SQLite, and complex assignments with extensive database tables, ERDs, flow charts, and UML diagrams.</li><li>I had a desire to expand my knowledge, including exploring technologies like Redis and Docker, which would be essential for more challenging future projects.</li></ul><p>Looking ahead, I plan to use Redis to build a high-traffic project and delve into various CI/CD tools for project deployment. My journey into web development has been fulfilling, and I am excited to continue learning and working on more ambitious projects in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cacb8833f569" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Singleton Design Pattern: Improving Code Structure and Management]]></title>
            <link>https://medium.com/@jielim36/understanding-singleton-design-pattern-improving-code-structure-and-management-8823463221a6?source=rss-5c85604199dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8823463221a6</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Lim Yee Jie]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 11:31:39 GMT</pubDate>
            <atom:updated>2023-10-29T11:31:39.705Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creational — Singleton Design Pattern</h3><p>Singleton provide a way for create a object. This pattern concern a single class, this class is only generate object of itself, and ensure that only one object can be generated, which means that we call this object in anywhere is still a same object (Data is shared). This class provide the ways to access the unique object, and you can access directly without instantiate an object of this class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/0*mWmdZIy4tu-7MSxe.jpg" /></figure><h3>Type of Singleton:</h3><p><strong>Eager Instantiation:</strong> Create an object when class loaded.<br><strong>Lazy Instantiation:</strong> Create an object when using it first time.</p><h3>Eager Singleton Instantiation</h3><p>There are two ways to implement a Eager pattern:</p><h4>Static variable type</h4><p>Step:</p><ol><li>constructor should be private: prevent outside create the object of this class</li><li>create a static object of this class. (Use static to make sure it is a unique object, and shared the same data anywhere)</li><li>create a static method provide the way for get instance of this class in the outside</li></ol><pre>public class EagerSingleton_One {<br>    //Step 2.<br>    private static EagerSingleton_One instance = new EagerSingleton_One();<br><br>    //Step 1.<br>    private EagerSingleton_One(){<br><br>    }<br><br>    //Step 3.<br>    public static EagerSingleton_One getInstance(){<br>        return instance;<br>    }<br><br>    public void printInfo(){<br>        System.out.println(&quot;My name is Jielim!&quot;);<br>    }<br><br>}</pre><h4>Static code block type</h4><p>Step:</p><ol><li>Create a static instance of this class but don’t assign it a value (null)</li><li>Using static code block to assign a value to instance object</li><li>(Same) create a private constructor</li><li>(Same) create a static method to return your instance</li></ol><pre>public class EagerSingleton_Two {<br><br>    private static EagerSingleton_Two instance;//not assign a value, so it is null<br>    <br>    static {<br>        instance = new EagerSingleton_Two();<br>    }<br>    private EagerSingleton_Two(){<br>    }<br>    public static EagerSingleton_Two getInstance(){<br>        return instance;<br>    }<br>}</pre><h4>Usage</h4><pre>public static void main(String[] args) {<br>        //create Singleton object<br>        EagerSingleton_One instance01 = EagerSingleton_One.getInstance();<br>        instance01.printInfo();//output:My name is Jielim!<br>}</pre><p>As you can see, we using EagerSingleton_One instance01 = EagerSingleton_One.getInstance(); instead of EagerSingleton_One eagerSingletonOne = new EagerSingleton_One();.</p><p>It is because we make the constructor into private access modifier to prevent other instance object create from external. We provide the method called getInstance() to allow external access to the same instance object.</p><pre>public static void main(String[] args) {<br>        EagerSingleton_One instance01 = EagerSingleton_One.getInstance();<br>        EagerSingleton_One instance02 = EagerSingleton_One.getInstance();<br>        System.out.println(&quot;Same :&quot; + (instance01 == instance02));<br>        //Output: Same :true<br>}</pre><p>As you can see, we create two instance by using the the getInstance() method, and we using == operator to <strong>compare the address of both</strong>, it&#39;s <strong>return true</strong>.</p><h4>Question:</h4><ol><li>Why it is a same instance object?<br>Because we using <strong>static</strong> keyword to declared an object.</li><li>What different between using static variable and static code block to implement Singleton?<br>Static variable type is loaded when the program starting; Static code block type is loaded when the first time you use/call this class such as EagerSingleton_One.xxXX().</li></ol><h3>Lazy Singleton Instantiation</h3><p>It is very <strong>similar</strong> with Eager Singleton，the difference is the getInstance() method.</p><pre>public class LazySingleton {<br>    private static LazySingleton instance;<br>    private LazySingleton(){}<br>    public static LazySingleton getInstance(){<br>        if (instance == null){<br>            instance = new LazySingleton();<br>        }<br>        return instance;<br>    }<br>}</pre><pre>public static void main(String[] args) {<br>    LazySingleton instance01 = LazySingleton.getInstance();<br>    LazySingleton instance02 = LazySingleton.getInstance();<br>    System.out.println(&quot;Same:&quot; + (instance01 == instance02));//true (same object)<br>}</pre><h3>What differences between Eager and Lazy Type of Singleton?</h3><ol><li><strong><em>Load timing:</em></strong> Eager Singleton instance object is loaded when program starting or Class loaded; Lazy Singleton is loaded when the getInstance() method is called for the first time. This affects the memory consumption of the entire program</li><li><strong><em>Thread Safety:</em></strong> Eager Singleton is thread safety but Lazy Singleton is not safety.</li></ol><p>Why Lazy Singleton is not safety in thread?</p><pre>public static LazySingleton getInstance(){<br>    if (instance == null){<br>        //inside if-statement point<br>        instance = new LazySingleton();<br>    }<br>    return instance;<br>}</pre><p>You can imagine that if two threads access getInstance() method at the same time and also deterimine instance == null, there is a probability that both threads judge null and create the object at the same time.</p><p>Resolve the thread safety problem of Lazy Sigleton</p><p>Idea: double verification</p><pre>public static LazySingleton getInstance() {<br>    if (instance == null) {<br>        //both threads judge null and come in at the same time, using synchronized keywords to make sure only on<br>        synchronized (LazySingleton.class) {<br>            //Only one thread is allowed to judge the condition at the same time<br>            if (instance == null) {<br>                instance = new LazySingleton();<br>            }<br>        }<br>    }<br>    return instance;<br>}</pre><p>Other ways to implement Lazy Singleton with Thread Safety</p><pre>public class LazySingleton_Two {<br>    private LazySingleton_Two(){}<br>    //static inner class<br>    private static class SingletonHolder{<br>        private static final LazySingleton_Two INSTANCE = new LazySingleton_Two();<br>    }<br>    public static LazySingleton_Two getInstance(){<br>        //when we called this method first time, static inner class will load and initialize the INSTACE object<br>        return SingletonHolder.INSTANCE;<br>    }<br>}</pre><p>Static inner class called SingletonHolder declared in the inside of Singleton_Two class, and the instance of the Single_Two declared in the SingletonHolder class. Because JVM will not load the static inner class in the process of the outer class, static inner class will be loaded and initialize static field when invoke/call the field or method of the static inner class.</p><h3>Eager Singleton with Enum</h3><blockquote><em>Charactericstic of Enum class:</em></blockquote><ul><li>Each Enum type inherit from java.lang.Enum, that means enum class can’t inherit others.</li><li>Each enum field is the instance of the enum class, same like: public static final Class INSTANCE = new Class();</li><li>Constructor of enum class is private modifier.</li><li>Using Class.instanceName to access the specific INSTANCE.</li></ul><pre>public enum EagerSingleton_Enum {<br>    //same like: public final static EagerSingleton_Enum INSTANCE = new EagerSingleton_Enum();<br>    INSTANCE;<br>    //constructor is private modifier<br>    EagerSingleton_Enum() {<br>        //code...<br>    }<br>    public void printSomething(){<br>        System.out.println(&quot;Hello Singleton!&quot;);<br>    }<br>}</pre><p>Usage:</p><pre>public static void main(String[] args) {<br>    EagerSingleton_Enum instance01 = EagerSingleton_Enum.INSTANCE;<br>    EagerSingleton_Enum instance02 = EagerSingleton_Enum.INSTANCE;<br>    System.out.println(instance01 == instance02);//output: true<br>    instance01.printSomething();//output: Hello Singleton!<br>}</pre><p>We are highly <strong>recommend</strong> using <strong>enum</strong> to implement a Singleton design pattern, because Enumeration is the only singleton pattern of all the singletons that is <strong>not broken</strong>.</p><p>There are <strong>3️ main scenarios that breaks Singleton</strong> even though we make it Thread Safe. They are:</p><ol><li><strong>Cloning</strong></li><li><strong>Deserialization</strong></li><li><strong>Reflection</strong></li></ol><h3>1. Cloning</h3><p>Example from <a href="https://salithachathuranga94.medium.com/stop-breaking-singleton-pattern-in-java-7bf7f87393c3">here</a></p><h3>2. Deserialization</h3><p>When we write a Singleton Object into byte stream, after performing read the object, we should get the same hash code if we have only one object.</p><pre>public class Client {<br>    public static void main(String[] args) throws Exception{<br>        //case one (normal Singleton)<br>        writeCaseOne2File();<br>        //output two times to compare hash code<br>        readCaseOneFromFile();<br>        readCaseOneFromFile();<br>        //case two (Enum Singleton)<br>        writeCaseTwo2File();<br>        readCaseTwoFromFile();<br>        readCaseTwoFromFile();<br>    }<br>    public static void readCaseOneFromFile() throws Exception{<br>        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(&quot;deserialization_caseOne.txt&quot;));<br>        EagerSingleton_One caseOne_first = (EagerSingleton_One) ois.readObject();<br>        System.out.println(&quot;Case one: &quot;+caseOne_first.hashCode());<br>        ois.close();<br>    }<br>    public static void writeCaseOne2File() throws Exception{<br>        EagerSingleton_One caseOne = EagerSingleton_One.getInstance();<br>        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(&quot;deserialization_caseOne.txt&quot;));<br>        oos.writeObject(caseOne);<br>        oos.close();<br>    }<br>    public static void readCaseTwoFromFile() throws Exception{<br>        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(&quot;deserialization_caseTwo.txt&quot;));<br>        EagerSingleton_Enum caseOne_first = (EagerSingleton_Enum) ois.readObject();<br>        System.out.println(&quot;Case Two: &quot;+caseOne_first.hashCode());<br>        ois.close();<br>    }<br>    public static void writeCaseTwo2File() throws Exception{<br>        EagerSingleton_Enum caseTwo = EagerSingleton_Enum.INSTANCE;<br>        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(&quot;deserialization_caseTwo.txt&quot;));<br>        oos.writeObject(caseTwo);<br>        oos.close();<br>    }<br>}</pre><pre>Output:<br>//Normal Singleton<br>Case one: 1793329556<br>Case one: 1334729950<br>//Enum Singleton<br>Case Two: 1174290147<br>Case Two: 1174290147</pre><p>As you can see, if we try to write and read an object of the singleton with the stream, in normal singleton will be break because we get the <strong>different hash code</strong> when reading two times. Instead, the <strong>same hash code</strong> can be obtained using the enum case.</p><p><strong>How to resolve the break problem of the normal singleton in deserialization?</strong></p><pre>public class EagerSingleton_One implements Serializable {<br>    private static EagerSingleton_One instance = new EagerSingleton_One();<br>    private EagerSingleton_One(){<br>    }<br>    public static EagerSingleton_One getInstance(){<br>        return instance;<br>    }<br>    public void printInfo(){<br>        System.out.println(&quot;My name is Jielim!&quot;);<br>    }<br>    //when executing deserialization, system will automatically invoke this method<br>    public Object readResolve(){<br>        return instance;<br>    }<br>}</pre><p>We add the method called readResolve() with Object return type. When executing deserialization, system will automatically invoke this method and wwe can get the same hash code now.</p><pre>Output:<br>//normal singleton<br>Case one: 2117255219<br>Case one: 2117255219<br>//enum singleton<br>Case Two: 1212899836<br>Case Two: 1212899836</pre><h3>3. Reflection break the singleton</h3><pre>public static void main(String[] args) throws Exception {<br>    Class&lt;EagerSingleton_One&gt; clazzOne = EagerSingleton_One.class;<br>        Constructor&lt;EagerSingleton_One&gt; constructor = clazzOne.getDeclaredConstructor();<br>        //cancel accessible<br>        constructor.setAccessible(true);<br>        EagerSingleton_One eagerSingletonOne_A = constructor.newInstance();<br>        EagerSingleton_One eagerSingletonOne_B = constructor.newInstance();<br>        System.out.println(eagerSingletonOne_A == eagerSingletonOne_B);//false<br>        //enum singleton<br>        Class&lt;EagerSingleton_Enum&gt; clazzEnum = EagerSingleton_Enum.class;<br>        EagerSingleton_Enum[] enumConstants_A = clazzEnum.getEnumConstants();<br>        System.out.println(enumConstants_A[0] == EagerSingleton_Enum.INSTANCE);//true<br>}</pre><p>In this case, we using reflection to create two instance of the singleton, and the result of the comparison of both addresses is false.</p><p><strong>How to prevent the break problem of the normal singleton in reflection?</strong></p><pre>public class EagerSingleton_One implements Serializable {<br>    private static EagerSingleton_One instance = null;<br>    private static boolean flag = false;<br>    private EagerSingleton_One() {<br>        synchronized (EagerSingleton_One.class){<br>            if (flag){<br>                throw new RuntimeException(&quot;You have broken Singleton class!&quot;);<br>            }<br>            flag = true;<br>        }<br>    }<br>    public static EagerSingleton_One getInstance() {<br>        if (instance == null) {<br>            synchronized (EagerSingleton_One.class) {<br>                if (instance == null) {<br>                    instance = new EagerSingleton_One();<br>                }<br>            }<br>        }<br>        return instance;<br>    }<br>}</pre><p>In this case, we prevent calling the constructor twice to safeguard against a broken singleton.</p><h3>References</h3><ol><li><a href="https://www.freecodecamp.org/news/the-basic-design-patterns-all-developers-need-to-know/">https://www.freecodecamp.org/news/the-basic-design-patterns-all-developers-need-to-know/</a></li><li><a href="https://salithachathuranga94.medium.com/stop-breaking-singleton-pattern-in-java-7bf7f87393c3">https://salithachathuranga94.medium.com/stop-breaking-singleton-pattern-in-java-7bf7f87393c3</a></li><li><a href="https://www.bilibili.com/video/BV1Np4y1z7BU?p=29&amp;vd_source=114500c2627a5627c7d30c7176c58bbb">https://www.bilibili.com/video/BV1Np4y1z7BU?p=29&amp;vd_source=114500c2627a5627c7d30c7176c58bbb</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8823463221a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>