This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

How to Use ConfigCat Feature Flags with Docker


Docker is a platform that allows builders to construct apps and run them in mini digital machines referred to as containers. Because of this, builders can simply concentrate on writing code without having to arrange or configure an atmosphere for working that code. Docker additionally permits simple software sharing as a result of its atmosphere is abstracted away from the host machine. This permits the containerized software to run on any host machine Docker is put in on. Builders can lengthen the performance of Docker’s desktop software with extensions. However the goodness would not cease there. You should use characteristic flags to manage smaller characteristic elements of those extensions with out rebuilding and updating them.



Introducing Characteristic Flags

Feature flags enable builders to modify options in software program purposes on or off remotely with out modifying the code. A characteristic flag works equally to a light-weight swap. By setting its boolean worth to both true or false you’ll be able to management whether or not a characteristic needs to be proven to customers or not.

The primary advantages of utilizing characteristic flags would come with:

  • By way of a easy GUI dashboard you’ll be able to toggle specific options on or off with out the necessity to edit and redeploy your software’s code.
  • If a brand new characteristic is deployed and is inflicting bugs, you’ll be able to simply roll it again by turning off its flag.
  • Characteristic flags give builders the liberty and confidence to experiment rapidly.
  • Conducting A/B exams could be streamlined when mixed with characteristic flags.

Importantly, you need to use characteristic flags in lots of programming languages or frameworks. ConfigCat presents an extensive list of SDKs for integrating its characteristic flag service in your expertise stack.



ConfigCat: A Cloud-Hosted Characteristic Flag Supplier

ConfigCat lets you handle your characteristic flags from an easy-to-use dashboard, together with the power to set concentrating on guidelines for releasing options to a selected phase of customers. These guidelines could be primarily based on nation, electronic mail, and customized identifiers resembling age, eye shade, and many others.

However let’s get to the purpose: Characteristic flags are cool however how will we use them with Docker?



Methods to Use ConfigCat Characteristic Flags with Docker

Docker presents builders a easy API to create extensions that add additional functionalities to the Docker desktop software. This may be achieved utilizing the Extensions SDK.

Within the upcoming part, I will present you construct and set up a easy extension that shows a desk of Docker containers at the moment current in your machine. We’ll then proceed so as to add a characteristic flag to manage the visibility of one among its baby elements.



Growing a Docker Desktop Extension

Let’s bounce proper into constructing our Docker desktop extension.

Earlier than getting began test when you’ve obtained the next conditions:

1. To get began, open up a terminal and level it to the folder the place you need the extension to stay. Then, arrange the listing on your extension and generate the wanted information with the next command:

docker extension init my-extension
Enter fullscreen mode

Exit fullscreen mode

To confirm that the generated extension works, construct and set up it utilizing the next instructions:

docker construct -t my-extension .
Enter fullscreen mode

Exit fullscreen mode

docker extension set up my-extension
Enter fullscreen mode

Exit fullscreen mode

If the above was profitable, you must see the extension out there in your Docker desktop software:

default quick start extension

2. The docker extension init my-extension command has additionally generated a backend service for the extension. For this demo, we’ll solely concentrate on the front-end so it’s secure to delete the backend folder. Replace the next information as follows to take away all references to the backend:

Dockerfile:

FROM --platform=$BUILDPLATFORM node:18.12-alpine3.16 AS client-builder
WORKDIR /ui
# cache packages in layer
COPY ui/package deal.json /ui/package deal.json
COPY ui/package-lock.json /ui/package-lock.json
RUN --mount=kind=cache,goal=/usr/src/app/.npm 
    npm set cache /usr/src/app/.npm && 
    npm ci
# set up
COPY ui /ui
RUN npm run construct

FROM alpine
LABEL org.opencontainers.picture.title="My extension" 
    org.opencontainers.picture.description="My superior Docker extension" 
    org.opencontainers.picture.vendor="Superior Inc." 
    com.docker.desktop.extension.api.model="0.3.4" 
    com.docker.extension.screenshots="" 
    com.docker.desktop.extension.icon="" 
    com.docker.extension.detailed-description="" 
    com.docker.extension.publisher-url="" 
    com.docker.extension.additional-urls="" 
    com.docker.extension.classes="" 
    com.docker.extension.changelog=""

COPY docker-compose.yaml .
COPY metadata.json .
COPY docker.svg .
COPY --from=client-builder /ui/construct ui
Enter fullscreen mode

Exit fullscreen mode

docker-compose.yaml

providers:
  my-extension:
    picture: ${DESKTOP_PLUGIN_IMAGE}
Enter fullscreen mode

Exit fullscreen mode

metadata.json

{
  "icon": "docker.svg",
  "vm": {
    "composefile": "docker-compose.yaml"
  },
  "ui": {
    "dashboard-tab": {
      "title": "My Extension",
      "src": "index.html",
      "root": "ui"
    }
  }
}
Enter fullscreen mode

Exit fullscreen mode

3. Modify the App.tsx file in order that the extension will show a desk of Docker containers in your system:

// ui/src/App.tsx
import React, { useEffect } from 'react';
import {
  Stack,
  Desk,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
} from "@mui/materials";
import { createDockerDesktopClient } from "@docker/extension-api-client";

//acquire docker desktop extension shopper
const ddClient = createDockerDesktopClient();

export perform App() {
  const [containers, setContainers] = React.useState<any[]>([]);

  const fetchAllContainers = async () => {
    ddClient.docker.cli.exec('ps', ['--all', '--format', '"{{json .}}"']).then((outcome) => {
      // outcome.parseJsonLines() parses the output of the command into an array of objects
      setContainers(outcome.parseJsonLines());
    });
  }

  useEffect(() => {
    // Get all containers
    fetchAllContainers();
  }, []);

  return (
      <Stack>
        <Typography information-testid="heading" variant="h3" function="title">
          Container checklist
        </Typography>
        <Typography
          information-testid="subheading"
          variant="body1"
          shade="textual content.secondary"
          sx={{ mt: 2 }}
        >
        Easy checklist of containers utilizing Docker Extensions SDK.
        </Typography>

        <TableContainer sx={{ mt: 2 }}>
          <Desk>
            <TableHead>
              <TableRow>
                <TableCell>Container id</TableCell>
                <TableCell>Picture</TableCell>
                <TableCell>Command</TableCell>
                <TableCell>Created</TableCell>
                <TableCell>Standing</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {containers.map((container) => (
                <TableRow
                  key={container.ID}
                  sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
                >
                  <TableCell>{container.ID}</TableCell>
                  <TableCell>{container.Picture}</TableCell>
                  <TableCell>{container.Command}</TableCell>
                  <TableCell>{container.CreatedAt}</TableCell>
                  <TableCell>{container.Standing}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Desk>
        </TableContainer>
      </Stack>
  );
}
Enter fullscreen mode

Exit fullscreen mode

To see the brand new adjustments, construct and replace the extension:

docker construct -t my-extension .
Enter fullscreen mode

Exit fullscreen mode

docker extension replace my-extension
Enter fullscreen mode

Exit fullscreen mode

Modified extension

The extension now shows a desk of all Docker containers in your machine. As a substitute of exhibiting all containers, together with those which can be turned off, let’s add a filter swap to show solely the working containers.

4. Modify the App.tsx file as follows:

// ui/src/App.tsx
import React, { useEffect } from 'react';
import {
  Stack,
  Desk,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
  Change,
  FormControlLabel,
  FormGroup,
} from "@mui/materials";
import { createDockerDesktopClient } from "@docker/extension-api-client";

//acquire docker desktop extension shopper
const ddClient = createDockerDesktopClient();

export perform App() {
  const [containers, setContainers] = React.useState<any[]>([]);

  const fetchAllContainers = async () => {
    ddClient.docker.cli.exec('ps', ['--all', '--format', '"{{json .}}"']).then((outcome) => {
      // outcome.parseJsonLines() parses the output of the command into an array of objects
      setContainers(outcome.parseJsonLines());
    });
  }

  const fetchRunningContainers = async () => {
    ddClient.docker.cli.exec('ps', ['--format', '"{{json .}}"']).then((outcome) => {
      // outcome.parseJsonLines() parses the output of the command into an array of objects
      setContainers(outcome.parseJsonLines());
    });
  }

  const handleFetchContainers = (occasion: React.ChangeEvent<HTMLInputElement>) => {
    if (occasion.goal.checked) {
      fetchRunningContainers();
    } else {
      fetchAllContainers();
    }
  }

  useEffect(() => {
    // Get all containers
    fetchAllContainers();
  }, []);

  return (
      <Stack>
        <Typography information-testid="heading" variant="h3" function="title">
          Container checklist
        </Typography>
        <Typography
          information-testid="subheading"
          variant="body1"
          shade="textual content.secondary"
          sx={{ mt: 2 }}
        >
        Easy checklist of containers utilizing Docker Extensions SDK.
        </Typography>

          <FormGroup sx={{ mt: 1 }}>
            <FormControlLabel management={<Change onChange={(occasion) => handleFetchContainers(occasion)} />} label="Present solely working containers" />
          </FormGroup>

        <TableContainer sx={{ mt: 2 }}>
          <Desk>
            <TableHead>
              <TableRow>
                <TableCell>Container id</TableCell>
                <TableCell>Picture</TableCell>
                <TableCell>Command</TableCell>
                <TableCell>Created</TableCell>
                <TableCell>Standing</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {containers.map((container) => (
                <TableRow
                  key={container.ID}
                  sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
                >
                  <TableCell>{container.ID}</TableCell>
                  <TableCell>{container.Picture}</TableCell>
                  <TableCell>{container.Command}</TableCell>
                  <TableCell>{container.CreatedAt}</TableCell>
                  <TableCell>{container.Standing}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Desk>
        </TableContainer>
      </Stack>
  );
}
Enter fullscreen mode

Exit fullscreen mode

5. Construct and replace the extension as we did earlier than, and you must see:

Modified extension with switch

6. Let’s create a characteristic flag within the ConfigCat dashboard with the next particulars. This characteristic flag will management the visibility of the filter swap:

Modified extension

Since we’re utilizing React, let’s set up and use ConfigCat’s React SDK.

7. Set up the React SDK with the next command:

npm i configcat-react
Enter fullscreen mode

Exit fullscreen mode

8. Within the primary.tsx file, Import the ConfigCatProvider and wrap the <App /> part utilizing it:

import { ConfigCatProvider } from "configcat-react"; // Newly added

import { App } from './App';

ReactDOM.createRoot(doc.getElementById("root") as HTMLElement).render(
  <React.StrictMode>
    {/*
      In the event you eject from MUI (which we do not suggest!), you must add
      the `dockerDesktopTheme` class to your root <html> component to get
      some minimal Docker theming.

      Newly added <ConfigCatProvider />
    */}
    <ConfigCatProvider sdkKey="YOUR-CONFIGCAT-SDK-KEY">
      <DockerMuiThemeProvider>
        <CssBaseline />
          <App />
      </DockerMuiThemeProvider>
    </ConfigCatProvider>
  </React.StrictMode>
);
Enter fullscreen mode

Exit fullscreen mode

9. Within the App.tsx file, add the next line beneath the prevailing import statements:

import { useFeatureFlag } from 'configcat-react';
Enter fullscreen mode

Exit fullscreen mode

10. Throughout the App() perform block, add the next hook:

const { worth: isFilterSwitchEnabled } = useFeatureFlag('filterswitch', false);
Enter fullscreen mode

Exit fullscreen mode

The isFilterSwitchEnabled will maintain a price of true when the characteristic flag (filterswitch) is enabled and false in any other case. Let’s use it to render the filter swap when it’s true:

{
  isFilterSwitchEnabled && 
  <FormGroup sx={{ mt: 1 }}>
    <FormControlLabel management={<Change onChange={(occasion) => handleFetchContainers(occasion)} />} label="Present solely working containers" />
  </FormGroup>
}
Enter fullscreen mode

Exit fullscreen mode



Take a look at Drive

Turning off the characteristic flag in your Dashboard will disguise the characteristic:

Turning off the feature flag

Extension with feature flag turned off

Curious about studying extra? Within the subsequent part, I will share some extra data that can make utilizing Docker and ConfigCat characteristic flags even simpler for you.



Finest Practices to Contemplate When Utilizing ConfigCat Characteristic Flags with Docker

Whereas there is no proper or fallacious manner to make use of characteristic flags generally, there are some finest practices that may make it easier to get probably the most out of utilizing them with Docker.



Growing Your Docker Extensions with Characteristic Flags in Thoughts

Think about you constructed and deployed your first Docker extension. Because it scales and extra customers hop on board, extra options are wanted, even ones you have not thought of. In the event you design the extension elements to be managed by characteristic flags, you’ll be able to simply decide how and when they’re launched.

What this implies is you can select to render every characteristic part in your code primarily based on the worth of its corresponding characteristic flag. This may be achieved by checking whether or not the flag’s boolean worth is about to true with a conditional IF-statement.



Optimizing for Sooner Efficiency

In my expertise utilizing ConfigCat, though it is comparatively quick, there are methods to additional optimize its efficiency and probably restrict the HTTP requests made by your containers for querying characteristic flag values. One approach to obtain that is by using a customized cache.

In the event you resolve to make use of a customized cache resembling Redis, you’ll be able to combine it together with your ConfigCat SDK shopper primarily based on the directions documented here. With this strategy, you’ll be able to unlock community request processes on the shopper aspect. It’s because your shopper SDK will as an alternative consider your characteristic flags primarily based on the cache information. Take a look at the using ConfigCat with Redis information to be taught extra.



Abstract of Key Factors

  • Docker is a software for constructing and sharing code in containerized environments.
  • ConfigCat is a cloud-hosted characteristic flag service that simplifies characteristic flag administration from a central dashboard.
  • A characteristic flag is sort of a swap for a characteristic. It may be used to indicate or disguise the characteristic it’s linked to.
  • The Docker extension SDK offers an API for builders to increase Docker desktop functionalities.
  • You should use characteristic flags in your Docker extension to manage characteristic elements with out the necessity to construct and redeploy the extension.
  • To benefit from utilizing ConfigCat characteristic flags with Docker, think about the most effective practices we have mentioned.



Conclusion

Some great benefits of utilizing Docker make it a horny selection for builders relating to deploying their purposes. This, in flip, facilitates easy sharing and deployment of those purposes, owing to the remoted environments created by Docker’s containerization strategy. By way of extensions, builders can incorporate additional functionalities into Docker. When mixed with characteristic flags, builders can readily deploy their extensions to the general public group and introduce new options effortlessly with a easy click on of a button.



References



Supply Code

Yow will discover the entire code for the extension here.



Additional Studying

If you would like to be taught extra, take a look at the next assets:

Keen to present what you discovered a attempt? Join a free-tier ConfigCat account here and keep on prime of the most recent posts and bulletins from ConfigCat on Twitter, Facebook, LinkedIn, and GitHub.



The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?