def finalize(self):
        """
        Finalizes the Dockerfile. Before the buffer is practically marked as read-only, the following Dockerfile
        commands are written:

        * ``RUN rm -R`` on each files marked for automatic removal;
        * ``VOLUME`` for shared volumes;
        * ``USER`` as the default user for following commands;
        * ``WORKDIR`` as the working directory for following commands;
        * ``SHELL`` if the default shell is to be changed;
        * ``ENTRYPOINT`` and ``CMD``, each formatted as a shell or exec command according to :attr:`command_shell`;
        * ``EXPOSE`` for exposed ports;
        * ``LABEL``, ``STOPSIGNAL``, and ``HEALTHCHECK`` instructions for the image;

        An attempt to finalize an already-finalized instance has no effect.
        """
        if self._finalized:
            return
        if self._remove_files:
            for filename in self._remove_files:
                self.prefix('RUN', 'rm -Rf', filename)
            self.blank()
        if self._volumes is not None:
            self.prefix('VOLUME', json.dumps(self._volumes))
        if self._cmd_user:
            self.prefix('USER', self._cmd_user)
        if self._cmd_workdir:
            self.prefix('WORKDIR', self._cmd_workdir)
        if self._shell:
            self.prefix('SHELL', self._shell)
        if self._entrypoint is not None:
            self.prefix('ENTRYPOINT', format_command(self._entrypoint, self._command_shell))
        if self._command is not None:
            self.prefix('CMD', format_command(self._command, self._command_shell))
        if self._expose is not None:
            self.prefix('EXPOSE', *format_expose(self._expose))
        if self._labels:
            self.prefix('LABEL', *format_labels(self._labels))
        if self._stopsignal:
            self.prefix('STOPSIGNAL', self._stopsignal)
        if self._healthcheck:
            self.prefix('HEALTHCHECK', self._healthcheck)
        super(DockerFile, self).finalize()