How to build a docker image with a working Nix inside it

You can simply pick the code that builds the official nix container and base your own container on it. I have a flake that contains (partly redacted):

inputs = {
   nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
   flake-utils.url = "github:numtide/flake-utils";
   nix = {
     url = "github:NixOS/nix";
     inputs.nixpkgs.follows = "nixpkgs";
   };
  };

outputs = { self, nix, nixpkgs, flake-utils }:

    flake-utils.lib.eachDefaultSystem (system:
      let
        pkgs = import nixpkgs { inherit system; };
        flakeRegistry = {
          nixos = {
            from = { type = "indirect"; id = "nixos"; };
            to = nixpkgs;
            exact = true;
          };
          nixpkgs = {
            from = { type = "indirect"; id = "nixpkgs"; };
            to = nixpkgs;
            exact = true;
          };
        };

        flakeRegistryJSON = (pkgs.formats.json { }).generate "flake-registry.json" {
          version = 2;
          flakes =
            pkgs.lib.mapAttrsToList (n: v: { inherit (v) from to exact; }) flakeRegistry;
        };

        containerInfo = {
          name = "mycontaner";
          tag = nixpkgs.rev;
        };
        flake-input-sources = pkgs.writeTextFile rec { name = "flake-inputs.log"; text = ''${nixpkgs.outPath} ${nix.outPath}''; destination = "/${name}"; };
        # use official nix container as base to get everything for flake-based building
        container-layered = pkgs.lib.throwIfNot (pkgs.stdenv.isLinux) "Docker images are only supported on Linux." (import ("${nix.outPath}" + "/docker.nix") {
          inherit (containerInfo) name tag;
          inherit pkgs;
          bundleNixpkgs=false;
          extraPkgs = [ pkgs.git pkgs.which pkgs.stdenvNoCC ] ++ [ flake-input-sources ];
          maxLayers = 111;
          nixConf = {
            experimental-features = [ "nix-command" "flakes" ];
          };
          flake-registry = flakeRegistryJSON;
        });

      in
      rec {
        devShell = pkgs.mkShell {
          buildInputs = [ run-packages dev-packages ];
          shellHook = '' echo Hello '';
        };
        packages = flake-utils.lib.flattenTree {
          container = container-layered;
        };

to create a flake-enabled Docker image that I use in CI.