In container terminals, containers are often moved to other stacks in order to access containers that need to leave the terminal earlier. We propose a new optimization model in which the containers can be moved in two different phases: a pre-processing and a relocation phase. To solve this problem, we develop an optimal branch-and-bound algorithm. Furthermore, we develop a local search heuristic because the problem is NP-hard. Besides that, we give a rule-based method to estimate the number of relocation moves in a bay. The local search heuristic produces solutions that are close to the optimal solution. Finally, for instances in which the benefits of moving containers in the two different phases are in balance, the solution of the heuristic yields significant improvement compared to the existing methods in which containers are only moved in one of the two phases.