In this paper, we study the thermodynamics and phase transition of BTZ black hole in a finite space region, namely a cavity. By imposing the boundary condition on the wall of the cavity and evaluating the Euclidean action, we derive the thermodynamic quantities and then construct the first law of thermodynamics for a static and neutral BTZ black hole, a rotating BTZ black hole and a charged BTZ black hole, respectively. We prove that heat capacities of these three types of black holes are always non-negative. Considering a grand canonical ensemble, we study the phase transitions between thermal AdS 3 space with M = −1 and the black holes. It shows that for the static and neutral BTZ black hole, the critical temperature (the temperature where the phase transition occurs) is only related to the cavity radius instead of AdS radius. For rotating and charged cases, there exists a cut off in the phase diagram, beyond which the phase transition could not occur. Consequently, we discuss the relationship between the allowed critical temperature and the ratio of AdS radius to cavity radius.