### Koji Environment Setup Example Source: https://github.com/kubernetes/kompose/blob/main/build/README.md Example commands to set up your environment for building on Koji, including installing the packager tools and authenticating with Kerberos. ```bash fedora-packager-setup kinit @FEDORAPROJECT.ORG ``` -------------------------------- ### Clone Example Project Source: https://github.com/kubernetes/kompose/blob/main/docs/maven-example.md Clone the example project from GitHub to start. ```bash $ git clone https://github.com/piyush1594/kompose-maven-example.git ``` ```bash $ cd kompose-maven-example ``` -------------------------------- ### Setup and Start Minishift Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Configure and start the minishift local OpenShift cluster using the KVM hypervisor. ```sh $ su - $ ln -s /var/lib/cdk-minishift-3.0.0/minishift /usr/bin/minishift $ minishift setup-cdk --force --default-vm-driver="kvm" $ ln -s /home/$(whoami)/.minishift/cache/oc/v3.5.5.8/oc /usr/bin/oc $ minishift start ``` -------------------------------- ### Install Gorilla Mux Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Install the gorilla/mux package using the go get command. Ensure your Go toolchain is correctly configured. ```sh go get -u github.com/gorilla/mux ``` -------------------------------- ### Start Minishift Source: https://github.com/kubernetes/kompose/blob/main/docs/maven-example.md If you need to test the application, start Minishift using this command. ```bash $ minishift start ``` -------------------------------- ### Start Minikube Cluster Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Initiates a local Kubernetes cluster using Minikube. Ensure Minikube is installed and configured. ```sh $ minikube start Starting local Kubernetes v1.7.5 cluster... Starting VM... Getting VM IP address... Moving files into cluster... Setting up certs... Connecting to cluster... Setting up kubeconfig... Starting cluster components... Kubectl is now configured to use the cluster ``` -------------------------------- ### Download Example Compose File Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Downloads a sample Docker Compose file to be used with Kompose. This command requires `wget` to be installed. ```sh wget https://raw.githubusercontent.com/kubernetes/kompose/main/examples/compose.yaml ``` -------------------------------- ### Full Mux-Based Server Example in Go Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md A complete, runnable example of a small Mux-based HTTP server in Go. It demonstrates setting up a router and handling a basic route. ```go package main import ( "net/http" "log" "github.com/gorilla/mux" ) func YourHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Gorilla!\n")) } func main() { r := mux.NewRouter() // Routes consist of a path and a handler function. r.HandleFunc("/", YourHandler) // Bind to a port and pass our router in log.Fatal(http.ListenAndServe(":8000", r)) } ``` -------------------------------- ### Install Kompose using Go Source: https://github.com/kubernetes/kompose/blob/main/docs/installation.md Install the latest development version of Kompose from the main branch using the Go toolchain. ```go go install github.com/kubernetes/kompose@latest ``` -------------------------------- ### Install Red Hat Development Suite and Kompose Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Install the Red Hat Development Suite and Kompose using yum. ```sh $ yum install rh-devsuite kompose -y ``` -------------------------------- ### Install Kompose on Windows using winget Source: https://github.com/kubernetes/kompose/blob/main/docs/installation.md Install Kompose on Windows using the winget package manager. ```powershell winget install Kubernetes.kompose ``` -------------------------------- ### Install Negroni Package Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/codegangsta/negroni/README.md Command to install the Negroni package using the Go toolchain. Ensure you have Go 1.1 or later installed. ```bash go get github.com/urfave/negroni ``` -------------------------------- ### Install Kompose via Maven Source: https://github.com/kubernetes/kompose/blob/main/docs/maven-example.md This command installs the 'kompose' tool on the host system using the Fabric8 Maven Plugin. ```bash $ mvn fabric8:install ``` -------------------------------- ### Basic Server Setup with Negroni Classic Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/codegangsta/negroni/README.md Demonstrates setting up a basic web server using Negroni's Classic mode, which includes default middlewares like Recovery, Logger, and Static file serving. Requires Go 1.1 or later. ```go package main import ( "fmt" "net/http" "github.com/urfave/negroni" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page!") }) n := negroni.Classic() // Includes some default middlewares n.UseHandler(mux) http.ListenAndServe(":3000", n) } ``` -------------------------------- ### Run a Negroni Server Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/codegangsta/negroni/README.md Use the `Run` function for a quick server setup, similar to `http.ListenAndServe`. It defaults to the PORT environment variable if no address is provided. ```go package main import ( "github.com/urfave/negroni" ) func main() { n := negroni.Classic() n.Run(":8080") } ``` -------------------------------- ### Custom Logger Format Example Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/codegangsta/negroni/README.md Example of setting a custom log format for the Logger middleware using a template string. ```go l.SetFormat("[{{.Status}} {{.Duration}}] - {{.Request.UserAgent}}") ``` -------------------------------- ### Start Gitlab, Postgresql, Redis with Docker Compose Source: https://github.com/kubernetes/kompose/blob/main/script/test/fixtures/gitlab/README.md Export environment variables from the envs file and then start the services using docker-compose. Edit the envs file to customize values. ```bash export $(cat envs) docker-compose up ``` -------------------------------- ### Define Init Container Command with Kompose Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md The `kompose.init.containers.command` label specifies the command to run in an init container. This is useful for setup tasks before the main application starts. ```yaml services: init-service: image: busybox labels: kompose.init.containers.command: ["echo", "Initializing..."] ``` -------------------------------- ### Install Kompose on Windows using Chocolatey Source: https://github.com/kubernetes/kompose/blob/main/docs/installation.md Install Kompose on Windows using the Chocolatey package manager. ```powershell choco install kubernetes-kompose ``` -------------------------------- ### Install Kompose on Linux Source: https://github.com/kubernetes/kompose/blob/main/index.md Download the Kompose binary for Linux, make it executable, and move it to a directory in your system's PATH. ```sh # Linux curl -L https://github.com/kubernetes/kompose/releases/download/v1.25.0/kompose-linux-amd64 -o kompose chmod +x kompose sudo mv ./kompose /usr/local/bin/kompose ``` -------------------------------- ### Configure Readiness Probe Start Period Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md Specify the initial period for the readiness probe to start successfully using this label. ```yaml services: web: image: custom-web labels: kompose.service.healthcheck.readiness.start_period: 30s ``` -------------------------------- ### Start Minishift Local OpenShift Cluster Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Initiates a local OpenShift cluster using the 'kvm' hypervisor. Ensure you have a virtualization environment set up. ```sh $ minishift start Starting local OpenShift cluster using 'kvm' hypervisor... -- Checking OpenShift client ... OK -- Checking Docker client ... OK -- Checking Docker version ... OK -- Checking for existing OpenShift container ... OK ... ``` -------------------------------- ### Setup Fabric8 Maven Plugin Source: https://github.com/kubernetes/kompose/blob/main/docs/maven-example.md Use this command to set up the Fabric8 Maven Plugin in your project. ```bash $ mvn io.fabric8:fabric8-maven-plugin:3.5.28:setup ``` -------------------------------- ### Install Kompose on macOS using Homebrew Source: https://github.com/kubernetes/kompose/blob/main/docs/installation.md Install the latest release of Kompose on macOS using the Homebrew package manager. ```bash brew install kompose ``` -------------------------------- ### Configure Readiness HTTP GET Path Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md Specify the HTTP path for the readiness probe using this label. ```yaml services: web: image: custom-web labels: kompose.service.healthcheck.readiness.http_get_path: /ready ``` -------------------------------- ### Serve Static Files with Mux in Go Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Use PathPrefix() combined with http.StripPrefix() and http.FileServer() to serve static files from a directory. This example sets up a server to serve files under /static/. ```go func main() { var dir string flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") flag.Parse() r := mux.NewRouter() // This will serve files under http://localhost:8000/static/ r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) srv := &http.Server{ Handler: r, Addr: "127.0.0.1:8000", // Good practice: enforce timeouts for servers you create! WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } log.Fatal(srv.ListenAndServe()) } ``` -------------------------------- ### Install Kompose on macOS Source: https://github.com/kubernetes/kompose/blob/main/index.md Download the Kompose binary for macOS, make it executable, and move it to a directory in your system's PATH. ```sh # macOS curl -L https://github.com/kubernetes/kompose/releases/download/v1.25.0/kompose-darwin-amd64 -o kompose chmod +x kompose sudo mv ./kompose /usr/local/bin/kompose ``` -------------------------------- ### Install Kompose on CentOS Source: https://github.com/kubernetes/kompose/blob/main/docs/installation.md Install Kompose on CentOS systems using the yum package manager, assuming EPEL repository is enabled. ```bash sudo yum -y install kompose ``` -------------------------------- ### Run Docker Compose Services Source: https://github.com/kubernetes/kompose/blob/main/script/test/fixtures/nginx-node-redis/README.md Use this command to start and run all services defined in your docker-compose.yml file. ```bash docker-compose up ``` -------------------------------- ### Get Services from Kubernetes/OpenShift Source: https://github.com/kubernetes/kompose/blob/main/docs/maven-example.md Query Kubernetes or OpenShift to list the services for your deployed application. ```bash $ oc get svc ``` -------------------------------- ### Walk Through Registered Routes Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Iterate over all registered routes in a router using the `Walk` function. This example prints details for each route, including path templates, regexps, methods, and queries. ```go package main import ( "fmt" "net/http" "strings" "github.com/gorilla/mux" ) func handler(w http.ResponseWriter, r *http.Request) { return } func main() { r := mux.NewRouter() r.HandleFunc("/", handler) r.HandleFunc("/products", handler).Methods("POST") r.HandleFunc("/articles", handler).Methods("GET") r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT") r.HandleFunc("/authors", handler).Queries("surname", "{surname}") err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error { pathTemplate, err := route.GetPathTemplate() if err == nil { fmt.Println("ROUTE:", pathTemplate) } pathRegexp, err := route.GetPathRegexp() if err == nil { fmt.Println("Path regexp:", pathRegexp) } queriesTemplates, err := route.GetQueriesTemplates() if err == nil { fmt.Println("Queries templates:", strings.Join(queriesTemplates, ",")) } queriesRegexps, err := route.GetQueriesRegexp() if err == nil { fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ",")) } methods, err := route.GetMethods() if err == nil { fmt.Println("Methods:", strings.Join(methods, ",")) } fmt.Println() return nil }) if err != nil { fmt.Println(err) } http.Handle("/", r) } ``` -------------------------------- ### Configure Readiness HTTP GET Port Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md Set the port for the HTTP readiness probe with this label. ```yaml services: web: image: custom-web labels: kompose.service.healthcheck.readiness.http_get_port: 8081 ``` -------------------------------- ### Integrate Negroni with net/http Server Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/codegangsta/negroni/README.md Pass a Negroni instance as the `Handler` to `http.Server` for more control. This example includes custom routes and server timeouts. ```go package main import ( "fmt" "log" "net/http" "time" "github.com/urfave/negroni" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page!") }) n := negroni.Classic() // Includes some default middlewares n.UseHandler(mux) s := &http.Server{ Addr: ":8080", Handler: n, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } log.Fatal(s.ListenAndServe()) } ``` -------------------------------- ### Configure Volume Type Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md Define the type of volume to be created. This example sets it to a persistentVolumeClaim. ```yaml services: db: image: postgres labels: kompose.volume.type: persistentVolumeClaim volumes: - db-data:/var/lib/postgresql/data ``` -------------------------------- ### Get Pods from Kubernetes/OpenShift Source: https://github.com/kubernetes/kompose/blob/main/docs/maven-example.md Query Kubernetes or OpenShift to list the running pods for your deployed service. ```bash $ oc get pods ``` -------------------------------- ### Specify Init Container Image with Kompose Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md Use the `kompose.init.containers.image` label to define the Docker image for an init container. This allows for specialized setup environments. ```yaml services: init-service: image: busybox labels: kompose.init.containers.image: busybox ``` -------------------------------- ### Negroni with Gorilla Mux Subrouter Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/codegangsta/negroni/README.md Example of applying Negroni middleware to a subrouter within Gorilla Mux. Ensure the subrouter path prefix is correctly linked. ```go router := mux.NewRouter() subRouter := mux.NewRouter().PathPrefix("/subpath").Subrouter().StrictSlash(true) subRouter.HandleFunc("/", someSubpathHandler) // "/subpath/" subRouter.HandleFunc("/:id", someSubpathHandler) // "/subpath/:id" // "/subpath" is necessary to ensure the subRouter and main router linkup router.PathPrefix("/subpath").Handler(negroni.New( Middleware1, Middleware2, negroni.Wrap(subRouter), )) ``` -------------------------------- ### Configure Readiness Probe Test Command Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md Specify the command to execute for the readiness probe using this label. This example uses curl to check an HTTP endpoint. ```yaml services: web: image: custom-web labels: kompose.service.healthcheck.readiness.test: ["CMD", "curl", "-f", "http://localhost:8081/ready"] ``` -------------------------------- ### Shared Middleware with Negroni `With()` Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/codegangsta/negroni/README.md Use the `With()` method to apply common middleware to multiple route groups, reducing redundancy. This example shows shared middleware for API and web routes. ```go router := mux.NewRouter() apiRoutes := mux.NewRouter() // add api routes here webRoutes := mux.NewRouter() // add web routes here // create common middleware to be shared across routes common := negroni.New( Middleware1, Middleware2, ) // create a new negroni for the api middleware // using the common middleware as a base router.PathPrefix("/api").Handler(common.With( APIMiddleware1, negroni.Wrap(apiRoutes), )) // create a new negroni for the web middleware // using the common middleware as a base router.PathPrefix("/web").Handler(common.With( WebMiddleware1, negroni.Wrap(webRoutes), )) ``` -------------------------------- ### Example cURL Request and Response Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Demonstrates a typical cURL request to a /foo endpoint configured with CORS headers and the expected HTTP response, including the Access-Control-Allow-Methods and Access-Control-Allow-Origin headers. ```bash curl localhost:8080/foo -v ``` ```text * Trying ::1... * TCP_NODELAY set * Connected to localhost (::1) port 8080 (#0) > GET /foo HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.59.0 > Accept: */* > < HTTP/1.1 200 OK < Access-Control-Allow-Methods: GET,PUT,PATCH,OPTIONS < Access-Control-Allow-Origin: * < Date: Fri, 28 Jun 2019 20:13:30 GMT < Content-Length: 3 < Content-Type: text/plain; charset=utf-8 < * Connection #0 to host localhost left intact foo ``` -------------------------------- ### Enable Red Hat Developer Tools Repository Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Enable necessary software repositories for Red Hat Enterprise Linux to install development tools. ```sh $ subscription-manager repos --enable rhel-7-server-devtools-rpms $ subscription-manager repos --enable rhel-server-rhscl-7-rpms ``` -------------------------------- ### Build URL from Named Route Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Retrieve a named route and construct its URL by providing values for route variables. This example builds the URL for the 'article' route. ```go url, err := r.Get("article").URL("category", "technology", "id", "42") ``` -------------------------------- ### Generate Spec File with gofed Source: https://github.com/kubernetes/kompose/blob/main/build/README.md Use gofed to automatically generate a .spec file for Kompose from a specific Git commit. Ensure gofed is installed and accessible. ```bash gofed repo2spec --detect github.com/kubernetes/kompose --commit 135165b39c55d29a5426479ded81eddd56bfbaf4 --with-extra --with-build -f ``` -------------------------------- ### Match Path Prefix in Go Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Use the PathPrefix() method on a router or subrouter to match requests that start with a specific path. This is commonly used for API versioning or grouping related routes. ```go r.PathPrefix("/products/") ``` -------------------------------- ### Configure Pod/CronJob Restart Policy (No Restart) Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md When the `restart` policy is set to `no`, Kompose creates a Pod or CronJob with a `Never` restart policy. This example also shows how to configure a CronJob with schedule, concurrency, and backoff limit. ```yaml version: '2' services: pival: image: perl command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"] restart: "no" labels: kompose.cronjob.schedule: "* * * * *" kompose.cronjob.concurrency_policy: "Forbid" kompose.cronjob.backoff_limit: "0" ``` -------------------------------- ### Define an Authentication Middleware Struct in Go Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md An example of a more complex middleware using a struct to hold state, in this case, a map of session tokens to usernames. This allows the middleware to maintain context across requests. ```go // Define our struct type authenticationMiddleware struct { tokenUsers map[string]string } // Initialize it somewhere func (amw *authenticationMiddleware) Populate() { amw.tokenUsers["00000000"] = "user0" amw.tokenUsers["aaaaaaaa"] = "userA" amw.tokenUsers["05f717e5"] = "randomUser" amw.tokenUsers["deadbeef"] = "user0" } // Middleware function, which will be called for each request func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token := r.Header.Get("X-Session-Token") if user, found := amw.tokenUsers[token]; found { // We found the token in our map log.Printf("Authenticated user %s\n", user) // Pass down the request to the next middleware (or final handler) next.ServeHTTP(w, r) } else { // Write an error and stop the handler chain http.Error(w, "Forbidden", http.StatusForbidden) } }) } ``` -------------------------------- ### Serve Kompose Site Locally Source: https://github.com/kubernetes/kompose/blob/main/docs/README.md Run this command to serve the Kompose documentation site locally. Access it by visiting localhost:4000 in your browser. ```sh bundle exec jekyll serve . ``` -------------------------------- ### Build URL with Host, Path, and Query Parameters Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Construct a full URL for a route that includes host, path, and query parameters. All specified variables must be provided. ```go url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42", "filter", "gorilla") ``` -------------------------------- ### Convert Compose to Kubernetes and Deploy Source: https://github.com/kubernetes/kompose/blob/main/index.md Download a sample docker-compose.yaml, convert it using kompose convert, apply the generated Kubernetes manifests with kubectl, and verify the deployment. ```sh $ wget https://raw.githubusercontent.com/kubernetes/kompose/master/examples/docker-compose-v3.yaml -O docker-compose.yaml $ kompose convert $ kubectl apply -f . $ kubectl get po NAME READY STATUS RESTARTS AGE frontend-591253677-5t038 1/1 Running 0 10s redis-master-2410703502-9hshf 1/1 Running 0 10s redis-replica-4049176185-hr1lr 1/1 Running 0 10s ``` -------------------------------- ### Build Kompose Binary with Make Source: https://github.com/kubernetes/kompose/blob/main/README.md Build the Kompose binary using the 'make bin' command. This requires 'make' and a compatible Golang version. ```console $ make bin ``` -------------------------------- ### Build RPM on Koji Source: https://github.com/kubernetes/kompose/blob/main/build/README.md Initiate a scratch build of the Kompose RPM on the Koji build system. Ensure your Koji environment is set up and you are authenticated. ```bash koji build --scratch rawhide kompose-0.3.0-0.1.git135165b.el7.centos.src.rpm ``` -------------------------------- ### Build Kompose Binary with Go Source: https://github.com/kubernetes/kompose/blob/main/README.md Build the Kompose binary directly using the 'go build' command. Specify the output file name as 'kompose' and the main Go file as 'main.go'. ```console $ go build -o kompose main.go ``` -------------------------------- ### Define Route with Host, Path, and Query Parameters Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Register a route that includes host, path, and query parameters. This allows for more complex URL matching and building. ```go r := mux.NewRouter() r.Host("{subdomain}.example.com"). Path("/articles/{category}/{id:[0-9]+}"). Queries("filter", "{filter}"). HandlerFunc(ArticleHandler). Name("article") ``` -------------------------------- ### Run Kompose Tests Source: https://github.com/kubernetes/kompose/blob/main/README.md Execute the test suite for Kompose using the 'make test' command. ```console $ make test ``` -------------------------------- ### Access Frontend Service via Minishift Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Open the 'frontend' service in the default browser using minishift. ```sh $ minishift openshift service frontend --namespace=myproject ``` -------------------------------- ### Open OpenShift Web Console Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Launch the OpenShift Web console in the default browser. ```sh $ minishift console ``` -------------------------------- ### Download Kompose Binary for Linux Source: https://github.com/kubernetes/kompose/blob/main/docs/installation.md Download the Kompose binary for Linux (amd64 and ARM64) using curl and make it executable. ```bash # Linux curl -L https://github.com/kubernetes/kompose/releases/download/v1.38.0/kompose-linux-amd64 -o kompose # Linux ARM64 curl -L https://github.com/kubernetes/kompose/releases/download/v1.38.0/kompose-linux-arm64 -o kompose chmod +x kompose sudo mv ./kompose /usr/local/bin/kompose ``` -------------------------------- ### Combine Middleware with Negroni.With() Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/codegangsta/negroni/README.md Illustrates using the `With` function to create a new Negroni instance that combines existing middleware with additional handlers. Useful for creating reusable middleware sets. ```go // middleware we want to reuse common := negroni.New() common.Use(MyMiddleware1) common.Use(MyMiddleware2) // `specific` is a new negroni with the handlers from `common` combined with the // the handlers passed in specific := common.With( SpecificMiddleware1, SpecificMiddleware2 ) ``` -------------------------------- ### Build Kompose Docker Image Source: https://github.com/kubernetes/kompose/blob/main/docs/installation.md Build a Docker image for Kompose from the official GitHub repository. ```bash docker build -t kompose https://github.com/kubernetes/kompose.git#main ``` -------------------------------- ### Configure Liveness HTTP Get Port with Kompose Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md Use the `kompose.service.healthcheck.liveness.http_get_port` label to define the port for HTTP liveness probes. This ensures probes are sent to the correct port. ```yaml services: web: image: custom-web ports: - "8080:8080" labels: kompose.service.healthcheck.liveness.http_get_port: 8080 ``` -------------------------------- ### Build Source RPM Locally Source: https://github.com/kubernetes/kompose/blob/main/build/README.md Build a source RPM (SRPM) and binary RPMs locally on CentOS after setting up the RPM build environment and preparing the Kompose source code. ```bash rpmbuild -ba kompose.spec ``` -------------------------------- ### Get Required Route Variable Names Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Use `GetVarNames()` to retrieve a list of all required variable names for a given route, which is useful for understanding URL construction requirements. ```go r := mux.NewRouter() r.Host("{domain}"). Path("/{group}/{item_id}"). Queries("some_data1", "{some_data1}"). Queries("some_data2", "{some_data2}"). Name("article") // Will print [domain group item_id some_data1 some_data2] fmt.Println(r.Get("article").GetVarNames()) ``` -------------------------------- ### Configure Liveness HTTP Get Path with Kompose Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md Set the `kompose.service.healthcheck.liveness.http_get_path` label to specify the HTTP path for liveness probes. This helps Kubernetes determine if a container is alive. ```yaml services: web: image: custom-web ports: - "8080:8080" labels: kompose.service.healthcheck.liveness.http_get_path: /health ``` -------------------------------- ### Check RPM Dependencies Source: https://github.com/kubernetes/kompose/blob/main/build/README.md Verify the dependencies of a built RPM package using the `rpm -qpR` command. Replace the placeholder path with the actual path to your RPM file. ```bash rpm -qpR RPMS/x86_64/kompose-0.3.0-0.1.git135165b.el7.centos.x86_64.rpm ``` -------------------------------- ### Route Order and Priority in Go Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Routes are matched in the order they are added to the router. The first route that matches all conditions will handle the request. Use PathPrefix("/") as a catch-all at the end. ```go r := mux.NewRouter() r.HandleFunc("/specific", specificHandler) r.PathPrefix("/").Handler(catchAllHandler) ``` -------------------------------- ### Expose Frontend Service in OpenShift Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Create an OpenShift route to make the 'frontend' service accessible. ```sh $ oc expose service/frontend ``` -------------------------------- ### Expose Service with OpenShift Route Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Creates an OpenShift route for the 'frontend' service, making it accessible. This command must be run after deploying the resources. ```sh $ oc expose service/frontend route "frontend" exposed ``` -------------------------------- ### Clone Kompose Repository Source: https://github.com/kubernetes/kompose/blob/main/README.md Clone the Kompose repository into your Go workspace. Ensure your GOPATH is set correctly. ```console $ git clone https://github.com/kubernetes/kompose.git $GOPATH/src/github.com/kubernetes/kompose ``` -------------------------------- ### Match HTTP Methods in Go Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Use the Methods() matcher to restrict routes to specific HTTP methods like GET or POST. This ensures that a route only responds to the intended request types. ```go r.Methods("GET", "POST") ``` -------------------------------- ### Create a Basic Logging Middleware in Go Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md A simple middleware that logs the request URI before passing the request to the next handler in the chain. It demonstrates the typical structure of a middleware function. ```go func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Do stuff here log.Println(r.RequestURI) // Call the next handler, which can be another middleware in the chain, or the final handler. next.ServeHTTP(w, r) }) } ``` -------------------------------- ### Download Kompose Binary for macOS Source: https://github.com/kubernetes/kompose/blob/main/docs/installation.md Download the Kompose binary for macOS (amd64 and ARM64) using curl and make it executable. ```bash # macOS curl -L https://github.com/kubernetes/kompose/releases/download/v1.38.0/kompose-darwin-amd64 -o kompose # macOS ARM64 curl -L https://github.com/kubernetes/kompose/releases/download/v1.38.0/kompose-darwin-arm64 -o kompose chmod +x kompose sudo mv ./kompose /usr/local/bin/kompose ``` -------------------------------- ### Run Kompose from Docker Image Source: https://github.com/kubernetes/kompose/blob/main/docs/installation.md Run the Kompose Docker image to convert Kubernetes manifests, mounting the current directory. ```bash docker run --rm -it -v $PWD:/opt -w /opt kompose kompose convert ``` -------------------------------- ### Clone Kompose Fork and Set Upstream Source: https://github.com/kubernetes/kompose/blob/main/docs/development.md Clone your forked Kompose repository into your Go path and add the upstream remote for tracking the main project. Ensure you have `$GOPATH` set. ```bash git clone https://github.com/$YOUR_GITHUB_USERNAME/kompose.git $GOPATH/src/github.com/kubernetes/kompose cd $GOPATH/src/github.com/kubernetes/kompose git remote add upstream 'https://github.com/kubernetes/kompose' ``` -------------------------------- ### Download Kompose Binary for Linux Source: https://github.com/kubernetes/kompose/blob/main/README.md Download the Kompose binary for Linux AMD64 architecture using curl. Ensure you have execute permissions and move it to a directory in your PATH. ```sh # Linux curl -L https://github.com/kubernetes/kompose/releases/download/v1.38.0/kompose-linux-amd64 -o kompose chmod +x kompose sudo mv ./kompose /usr/local/bin/kompose ``` -------------------------------- ### Add Custom Middleware using Use() Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/codegangsta/negroni/README.md Demonstrates adding a custom middleware function to a Negroni instance using the `Use` method. The middleware must be cast to `negroni.HandlerFunc`. ```go n := negroni.New() n.Use(negroni.HandlerFunc(MyMiddleware)) ``` -------------------------------- ### Implement Graceful Server Shutdown in Go Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md This snippet shows how to set up an HTTP server with Gorilla Mux and implement graceful shutdown. It listens for SIGINT signals and shuts down the server within a configurable timeout. Ensure the `graceful-timeout` flag is set appropriately for your application's needs. ```go package main import ( "context" "flag" "log" "net/http" "os" "os/signal" "time" "github.com/gorilla/mux" ) func main() { var wait time.Duration flag.DurationVar(&wait, "graceful-timeout", time.Second * 15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m") flag.Parse() r := mux.NewRouter() // Add your routes as needed srv := &http.Server{ Addr: "0.0.0.0:8080", // Good practice to set timeouts to avoid Slowloris attacks. WriteTimeout: time.Second * 15, ReadTimeout: time.Second * 15, IdleTimeout: time.Second * 60, Handler: r, // Pass our instance of gorilla/mux in. } // Run our server in a goroutine so that it doesn't block. go func() { if err := srv.ListenAndServe(); err != nil { log.Println(err) } }() c := make(chan os.Signal, 1) // We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C) // SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught. signal.Notify(c, os.Interrupt) // Block until we receive our signal. <-c // Create a deadline to wait for. ctx, cancel := context.WithTimeout(context.Background(), wait) defer cancel() // Doesn't block if no connections, but will otherwise wait // until the timeout deadline. srv.Shutdown(ctx) // Optionally, you could run srv.Shutdown in a goroutine and block on // <-ctx.Done() if your application should wait for other services // to finalize based on context cancellation. log.Println("shutting down") os.Exit(0) } ``` -------------------------------- ### Convert Compose to OpenShift Manifests Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md Use the --provider openshift flag to target OpenShift for the conversion. ```sh $ kompose --provider openshift --file compose.yaml convert ``` -------------------------------- ### Match Host Pattern in Go Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Use mux.NewRouter() to create a new router and then use the Host() method to match specific domain or subdomain patterns. This is useful for routing requests based on the host header. ```go r := mux.NewRouter() // Only matches if domain is "www.example.com". r.Host("www.example.com") // Matches a dynamic subdomain. r.Host("{subdomain:[a-z]+}.example.com") ``` -------------------------------- ### Access Minishift Service Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Opens the specified service ('frontend' in the 'myproject' namespace) in the default browser using Minishift. Requires the service to be exposed. ```sh $ minishift openshift service frontend --namespace=myproject Opening the service myproject/frontend in the default browser... ``` -------------------------------- ### Generate Bundled Dependencies Source: https://github.com/kubernetes/kompose/blob/main/build/README.md Run the parsedeps.go script within the Kompose source directory to generate bundled dependencies. This is a precursor to building the RPM. ```bash go run parsedeps.go ``` -------------------------------- ### Access Service via Minishift Source: https://github.com/kubernetes/kompose/blob/main/docs/maven-example.md Open the deployed Springboot service in your default browser using Minishift. ```bash $ minishift openshift service --in-browser springboot-compose ``` -------------------------------- ### Build URL with Subrouter Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Demonstrates building a URL when routes are defined within a subrouter. The parent router is used to access the named route. ```go r := mux.NewRouter() s := r.Host("{subdomain}.example.com").Subrouter() s.Path("/articles/{category}/{id:[0-9]+}"). HandlerFunc(ArticleHandler). Name("article") // "http://news.example.com/articles/technology/42" url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42") ``` -------------------------------- ### Convert Compose with Multiple Files to Kubernetes Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md Provide multiple compose files to merge their configurations. Later files override common configurations. ```sh $ kompose -f compose.yaml -f compose.yaml convert ``` -------------------------------- ### Open Minishift Console Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Launches the OpenShift Web console in the default browser, providing a GUI for managing the cluster and deployed applications. ```sh $ minishift console Opening the OpenShift Web console in the default browser... ``` -------------------------------- ### Map HTTP Handlers with Negroni Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/codegangsta/negroni/README.md Shows how to map standard Go `http.Handler`s, such as those created with `http.NewServeMux`, to a Negroni instance using `UseHandler`. ```go n := negroni.New() mux := http.NewServeMux() // map your routes n.UseHandler(mux) http.ListenAndServe(":3000", n) ``` -------------------------------- ### Deploy Application Source: https://github.com/kubernetes/kompose/blob/main/docs/maven-example.md Deploy the application to Kubernetes or OpenShift using the Fabric8 Maven Plugin. ```bash $ mvn fabric8:deploy ``` -------------------------------- ### Custom Build and Push Commands in Kompose Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md Use these flags to specify custom commands for building and pushing images when Kompose's default Docker integration is not sufficient. This allows integration with alternative container solutions. ```bash kompose -f convert --build-command 'whatever command --you-use' --push-command 'whatever command --you-use' ``` -------------------------------- ### Tagging a Release with Git Source: https://github.com/kubernetes/kompose/blob/main/RELEASE.md Use this command to create a signed Git tag for a new release. Ensure you replace $VERSION with the actual release version. ```bash git tag -s $VERSION ``` -------------------------------- ### Build URL Host and Path Separately Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Use `URLHost()` and `URLPath()` methods to build only the host or path component of a URL for a given route. ```go host, err := r.Get("article").URLHost("subdomain", "news") ``` ```go path, err := r.Get("article").URLPath("category", "technology", "id", "42") ``` -------------------------------- ### Describe Frontend Service Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Retrieves detailed information about the 'frontend' service in Kubernetes. This command is useful for debugging and understanding service configuration. ```sh $ kubectl describe svc frontend Name: frontend Namespace: default Labels: service=frontend Selector: service=frontend Type: LoadBalancer IP: 10.0.0.183 LoadBalancer Ingress: 123.45.67.89 Port: 80 80/TCP NodePort: 80 31144/TCP Endpoints: 172.17.0.4:80 Session Affinity: None No events. ``` -------------------------------- ### Download Kompose Binary for macOS Source: https://github.com/kubernetes/kompose/blob/main/README.md Download the Kompose binary for macOS AMD64 architecture using curl. Ensure you have execute permissions and move it to a directory in your PATH. ```sh # macOS curl -L https://github.com/kubernetes/kompose/releases/download/v1.38.0/kompose-darwin-amd64 -o kompose chmod +x kompose sudo mv ./kompose /usr/local/bin/kompose ``` -------------------------------- ### Access Service with Minikube Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Opens the specified service in your default web browser using Minikube's built-in functionality. This is a convenient way to access services deployed locally. ```sh $ minikube service frontend ``` -------------------------------- ### Add Middleware to a Mux Router in Go Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Demonstrates how to register a middleware function with a Mux router using the `Use()` method. This middleware will be executed for all incoming requests handled by the router. ```go r := mux.NewRouter() r.HandleFunc("/", handler) r.Use(loggingMiddleware) ``` -------------------------------- ### Basic Route Registration Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Register URL paths with corresponding handlers using mux.NewRouter(). This is compatible with the standard http.Handle function. ```go func main() { r := mux.NewRouter() r.HandleFunc("/", HomeHandler) r.HandleFunc("/products", ProductsHandler) r.HandleFunc("/articles", ArticlesHandler) http.Handle("/", r) } ``` -------------------------------- ### Negroni Static File Serving Middleware Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/codegangsta/negroni/README.md Serve static files from the filesystem using `negroni.NewStatic`. If a file is not found, it proxies the request to the next middleware. For 404 behavior on missing files, consider `http.FileServer`. ```go package main import ( "fmt" "net/http" "github.com/urfave/negroni" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page!") }) // Example of using a http.FileServer if you want "server-like" rather than "middleware" behavior // mux.Handle("/public", http.FileServer(http.Dir("/home/public"))) n := negroni.New() n.Use(negroni.NewStatic(http.Dir("/tmp"))) n.UseHandler(mux) http.ListenAndServe(":3002", n) } ``` -------------------------------- ### Register Authentication Middleware with Mux Router in Go Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Shows how to instantiate and register a stateful authentication middleware with a Mux router. The middleware checks for a session token in the request headers. ```go r := mux.NewRouter() r.HandleFunc("/", handler) amw := authenticationMiddleware{tokenUsers: make(map[string]string)} amw.Populate() r.Use(amw.Middleware) ``` -------------------------------- ### Convert Docker Compose to Kubernetes Manifests Source: https://github.com/kubernetes/kompose/blob/main/docs/index.md Use `kompose convert` to transform a `docker-compose.yaml` file into Kubernetes manifest files. Apply the generated manifests using `kubectl apply`. ```bash $ kompose convert -f compose.yaml $ kubectl apply -f . $ kubectl get po NAME READY STATUS RESTARTS AGE frontend-591253677-5t038 1/1 Running 0 10s redis-leader-2410703502-9hshf 1/1 Running 0 10s redis-replica-4049176185-hr1lr 1/1 Running 0 10s ``` -------------------------------- ### Run Negroni Server Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/codegangsta/negroni/README.md Command to run a Go server application that uses the Negroni middleware. ```bash go run server.go ``` -------------------------------- ### Implement Recovery Middleware in Go Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/codegangsta/negroni/README.md Use the Recovery middleware to catch panics and respond with a 500 status code. Attach a PanicHandlerFunc to report errors to external services. ```go package main import ( "net/http" "github.com/urfave/negroni" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { panic("oh no") }) n := negroni.New() n.Use(negroni.NewRecovery()) n.UseHandler(mux) http.ListenAndServe(":3003", n) } ``` ```go package main import ( "net/http" "github.com/urfave/negroni" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { panic("oh no") }) n := negroni.New() recovery := negroni.NewRecovery() recovery.PanicHandlerFunc = reportToSentry n.Use(recovery) n.UseHandler(mux) http.ListenAndServe(":3003", n) } func reportToSentry(info *negroni.PanicInformation) { // write code here to report error to Sentry } ``` ```go package main import ( "net/http" "github.com/urfave/negroni" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { panic("oh no") }) n := negroni.New() recovery := negroni.NewRecovery() recovery.Formatter = &negroni.HTMLPanicFormatter{} n.Use(recovery) n.UseHandler(mux) http.ListenAndServe(":3003", n) } ``` -------------------------------- ### Path Variables with Default Matching Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/gorilla/mux/README.md Define routes with path variables using the {name} format. Variables match any character until the next slash. ```go r := mux.NewRouter() r.HandleFunc("/products/{key}", ProductHandler) r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) ``` -------------------------------- ### Enable Fish Autocompletion for Kompose Source: https://github.com/kubernetes/kompose/blob/main/README.md Pipe the Kompose completion script output to source for Fish shell to enable command-line autocompletion. ```sh # Fish autocompletion kompose completion fish | source ``` -------------------------------- ### Convert Compose to Kubernetes Manifests Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md Use this command to convert a compose.yaml file to Kubernetes manifests. Kubernetes is the default provider. ```sh $ kompose --file compose.yaml convert ``` -------------------------------- ### Define Custom Negroni Middleware Source: https://github.com/kubernetes/kompose/blob/main/examples/web/vendor/github.com/codegangsta/negroni/README.md Illustrates how to define a custom middleware function for Negroni. Middleware functions take ResponseWriter, Request, and the next HandlerFunc in the chain. ```go func MyMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { // do some stuff before next(rw, r) // do some stuff after } ``` -------------------------------- ### Enable Bash Autocompletion for Kompose Source: https://github.com/kubernetes/kompose/blob/main/README.md Source the Kompose completion script for Bash to enable command-line autocompletion. Add this line to your .bashrc file for persistence. ```sh # Bash (add to .bashrc for persistence) source <(kompose completion bash) ``` -------------------------------- ### Convert Compose using Environment Variables Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md Specify compose files using the COMPOSE_FILE environment variable for conversion. ```sh $ COMPOSE_FILE="compose.yaml alternative-compose.yaml" kompose convert ``` -------------------------------- ### Convert Compose File to OpenShift Resources Source: https://github.com/kubernetes/kompose/blob/main/docs/getting-started.md Converts a 'compose.yaml' file into OpenShift-specific YAML resources using Kompose. The output files are created in the current directory. ```sh $ kompose convert --provider=openshift INFO OpenShift file "frontend-service.yaml" created INFO OpenShift file "redis-leader-service.yaml" created INFO OpenShift file "redis-replica-service.yaml" created INFO OpenShift file "frontend-deploymentconfig.yaml" created INFO OpenShift file "frontend-imagestream.yaml" created INFO OpenShift file "redis-leader-deploymentconfig.yaml" created INFO OpenShift file "redis-leader-imagestream.yaml" created INFO OpenShift file "redis-replica-deploymentconfig.yaml" created INFO OpenShift file "redis-replica-imagestream.yaml" created ``` -------------------------------- ### Convert Compose to Kubernetes Resources Source: https://github.com/kubernetes/kompose/blob/main/README.md Use this command to convert a compose.yaml file into Kubernetes deployment and service YAML files. The output indicates which Kubernetes files are created. ```sh $ kompose convert -f compose.yaml INFO Kubernetes file "frontend-service.yaml" created INFO Kubernetes file "redis-leader-service.yaml" created INFO Kubernetes file "redis-replica-service.yaml" created INFO Kubernetes file "frontend-deployment.yaml" created INFO Kubernetes file "redis-leader-deployment.yaml" created INFO Kubernetes file "redis-replica-deployment.yaml" created ``` -------------------------------- ### Configure Readiness Probe Timeout Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md Set the timeout for the readiness probe with this label. ```yaml services: web: image: custom-web labels: kompose.service.healthcheck.readiness.timeout: 5s ``` -------------------------------- ### Configure Pod/CronJob Restart Policy (On Failure) Source: https://github.com/kubernetes/kompose/blob/main/docs/user-guide.md When the `restart` policy is set to `on-failure`, Kompose creates a Pod or CronJob with a `OnFailure` restart policy. ```yaml version: '2' services: pival: image: perl command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"] restart: "on-failure" ```