'Build an image and tag it in the local Docker repository.
:param dict dockerfile_variables: A dictionary of replacements which
will be applied to a `Dockerfile.in` template file if such a file
exists.
:return: ``Deferred bytes`` with the tag name applied to the built
image.'

def build(self, dockerfile_variables=None):

    if (dockerfile_variables is None):
        dockerfile_variables = {}
    working_dir = FilePath(self.test.mktemp())
    working_dir.makedirs()
    docker_dir = working_dir.child('docker')
    shutil.copytree(self.source_dir.path, docker_dir.path)
    template_file = docker_dir.child('Dockerfile.in')
    docker_file = docker_dir.child('Dockerfile')
    if (template_file.exists() and (not docker_file.exists())):
        self._process_template(template_file, docker_file, dockerfile_variables)
    tag = ('flockerlocaltests/' + random_name(self.test).lower())
    command = ['docker', 'build', '--force-rm', ('--tag=%s' % (tag,)), docker_dir.path]
    d = logged_run_process(reactor, command)
    if self.cleanup:
        def remove_image():
            client = DockerClient(version='1.15')
            for container in client.containers():
                if (container[u'Image'] == (tag + ':latest')):
                    client.remove_container(container[u'Names'][0])
            client.remove_image(tag, force=True)
        self.test.addCleanup(remove_image)
    return d.addCallback((lambda ignored: tag))
